I have tried to search google and here about my question but havent found the exact answer which I could use. So I am asking here. Hope to find help.
I have some input fields in a form and want to show a DIV using jQuery. The details (pseudo-logic) are as follows.
V1: <input type="radio" name="rad" value="v1" />
V2: <input type="radio" name="rad" value="v2" />
<select name="sel">
<option value="o1">o1</option>
<option value="o2">o2</option>
</select>
Now, based on selection, the jQuery will generate the text in an initially empty hidden div based on data filled in form fields.
For example, as it may be shown
<div id="d1">
The calculated value for rad(o1) & o2 & t1 is "value1"
</div>
If it was only for PHP, the simple code I could use, to be processed in another php file, would be (using mysql query, and I am aware of real escape strings, just not mentioning here),
$radioBtn = $_POST['rad'];
$selDrpDn = $_POST['sel'];
$textData = $_POST['t1'];
//Using this query,
$queryString = mysql_query("SELECT * FROM mobiles WHERE jobType = '$radioBTN' AND modelName = '$selDrpDn' AND compName = '$textData'");
Not sure if this answers your question...
$(function() {
$("select[name='sel'], input[name='rad']").on("change",function() {
$('#d1').html("You selected : " + this.value).show();
}
});
that's using the form code and div sample you gave above.
Related
In my little application I have owner table in my database. Every owner has his ID, name, address and description (those are columns of this table).
On my website I have select element where you can choose owners.
Under this select I have 3 inputs (one for name, one for address and one for description).
When I change the option in my select element I would like to fill all inputs with the data from my database using AJAX.
My PHP:
<?php
$sql_select=$mysqli->prepare("SELECT id, name FROM owner ORDER BY id DESC");
$sql_select->execute();
$sql_select->store_result();
$sql_select->bind_result($id_owner, $name_owner);
$select = $_POST['owner'];
echo "<option value=0 ".selected.">Select...</option>";
while($sql_select->fetch()) {
if($select == $id_owner){
$selected="selected";
}
else {
$selected="";
}
echo "<option value=".$id_owner." ".$selected." data-id=".$id_owner.">".$id_owner." ".$name_owner."</option>";
}
?>
<label for="owner_name">Owner name</label>
<input id="owner_name" name="owner_name" type="text">
<label for="owner_address">Owner address</label>
<input id="owner_address" name="owner_address" type="text">
<label for="owner_description">Owner description</label>
<input id="owner_description" name="owner_description" type="text">
Rendered HTML:
<select id="owner" name="owner">
<option value="0" selected>Select...</option>
<option value="1" data-id="1">1 ABC</option>
<option value="2" data-id="2">2 DEF</option>
<option value="3" data-id="3">3 GHI</option>
</select>
<label for="owner_name">Owner name</label>
<input id="owner_name" name="owner_name" type="text">
<label for="owner_address">Owner address</label>
<input id="owner_address" name="owner_address" type="text">
<label for="owner_description">Owner description</label>
<input id="owner_description" name="owner_description" type="text">
This above code reads data from MySQL and creates options for select.
So far so good.
I was able to achieve my goal by setting data-name, data-address and data-description attributes in my HTML and assign to this 3 attributes proper data from the database to every option in my select and then use jQuery to fill the inputs. It looks like this after rendering PHP:
HTML:
<option value="0" selected>Select...</option>
<option value="1" data-id="1" data-name="ABC" data-address="London" data-description="Description of ABC owner">1 ABC</option>
<option value="2" data-id="2" data-name="DEF" data-address="Birmingham" data-description="Description of DEF owner">2 DEF</option>
<option value="3" data-id="3" data-name="GHI" data-address="Manchester" data-description="Description of GH~I owner">3 GHI</option>
JS:
$('#owner').change(function () {
var changedOption = $(this).find('option:selected');
var ownerName = changedOption.attr('data-name');
var ownerAddress = changedOption.attr('data-address');
var ownerDescription = changedOption.attr('data-description');
$('#owner_name').val(ownerName);
$('#owner_address').val(ownerAddress);
$('#owner_description').val(ownerDescription);
});
But there is a problem, imagine I have 1000 owners and think how much data would have to be assign into HTML. I would like to read data from my database on every change of my select using AJAX to avoid using HTML data-attributes.
Little example on CODEPEN to see what I mean exactly.
Can someone give me a clue where to start?
Say for example you wanted to make a request to a url and get a JSON response back containing the data you need (id, name, etc), something like this:
{
"ID":"1",
"name":"Bobby Longsocks",
"address":"some place",
"description":"A description here"
}
Using jQuery there are various ways to do what you need to now that you have the data in this format, one way would be to use $.get - which is appropriate for this example as that is what the PHP below will be looking for.
You could do something like this:
$('body').on('change', '#owner', function () {
var changedOption = $(this).find('option:selected').val();
var data = {
"user_id" : changedOption
};
$.get('ajax.php', data, function (response) {
$('#owner_name').empty().html(response.name);
$('#owner_addr').empty().html(response.address);
$('#owner_desc').empty().html(response.description);
}, 'json')
});
If the user selection was this:
<option value="1" data-id="1">1 ABC</option>
The requested url will be ajax.php?user_id=1
So... To get that response using PHP you can use json_encode to send back a JSON response to the client:
Lets say you have a file on your server called ajax.php where the following php will live:
(I prefer PDO so I will use that as a quick example)
<?php
try {
// Set up the response
$response = array();
// DB details
$db = new PDO(your_db_details);
// Read
if ( $_SERVER['REQUEST_METHOD'] == "GET" ) {
// Dont forget to sanitize!
$user_id = $_GET['user_id'];
// Build the query
$stmt = $db->query("SELECT `ID`, `name`, `address`, `description` FROM `your_table` WHERE `id` = '$user_id'");
if ($user_id) {
// If the ID is set, fetch the record
$response = $stmt->fetch(PDO::FETCH_ASSOC);
}
else {
// Do something if no id was set
}
// Encode it as JSON and ship it back
echo json_encode($response);
}
} catch(Exception $e) {
// Do some error handling
}
?>
Which will return the response we started with.
First, create a select field with a list of users so it shows their name, and uses the userId as the value.
Create a PHP file that can receive the userId ($_POST['user_id']), grab the user from the database, put the details you need for the user into an array. Then convert the array to JSON and echo it. echo json_encode($userArray);
In your HTML, use jQuery/Ajax to post the value of the select field to your PHP page. It will response with some JSON containing the users details, then you can put these values into the relevant fields.
See the jquery ajax documentation http://api.jquery.com/jquery.getjson/
I' new to HTML and PHP and was wondering if anyone out there could help me with a question... I'm trying to code a form that submits a selection from one menu OR another and, depending on which is chosen sends the data to one of two different PHP pages.
<form id="form1" method="post" action="">
<label for="SubjectID">Text Books by Subject</label>
</p>
<p>
<select "name="SubjectID" id="SubjectID">
<?php do { ?>
<option value="<?php echo $row_rsSubject['SubjectID']?>"><?php echo $row_rsSubject['SubjectName']?></option>
<?php } while ($row_rsSubject = mysql_fetch_assoc($rsSubject));
$rows = mysql_num_rows($rsSubject);
if($rows > 0) {
mysql_data_seek($rsSubject, 0);
$row_rsSubject = mysql_fetch_assoc($rsSubject);
} ?>
</select>
</p>
<p>
——— OR ———
</p>
<p>
<select name="CourseID" id="CourseID">
<?php do { ?>
<option value="<?php echo $row_rsCourse['CourseID']?>"><?php echo $row_rsCourse['CourseID']?></option>
<?php } while ($row_rsCourse = mysql_fetch_assoc($rsCourse));
$rows = mysql_num_rows($rsCourse);
if($rows > 0) {
mysql_data_seek($rsCourse, 0);
$row_rsCourse = mysql_fetch_assoc($rsCourse);
} ?>
</select>
</p>
<p>
<label for="CourseID">Text Books by Course</label>
</form>
So, the action should be (depending on which menu the user selects from) that the form submits to either subject.php or course.php, and I can't figure out how to do that with a single submit button. Can anyone help me?
first set onchange event to select:
<select name="CourseID" id="CourseID" onchange='myFunc(this)'>
Then:
<script>
function myFunc(element){
// set the form action depends on option chosen
// element.setAttribute('action', 'yourPageLink' );
}
</script>
You could update the action attribute with javascript when the user changes his selection, directing him to the relevant page.
Otherwise, why not submit to a single function and depending on the users selection call the relevant function?
Honestly I would use jquery's $.post to do this. To the best of my knowledge you can't really do that with straight html, and php is executed before the page loads so that's no help. With JQuery you could set an action to the button to call a function. Then your function could check the value of the select and pass the proper url to the $.post function.
You can read about that particular jquery function here: http://api.jquery.com/jQuery.post/
If you're not familiar with JQuery it's really easy to use with just a bit of reading if you're good with JavaScript.
Why not have a radio button in the form whose posted form value is processed by a central PHP form handler? That way, depending on what is entered on the radio button, you can process the request as necessary.
This might not be the answer you are looking for, but I am not clear if you want the user to be able to alter the destination or what.
I'm trying to change a series of links by inserting values from a dropdown box. I found this straight forward to do with php (code below) but I'd like to be able to change the links without 1) having a page refresh (these links are near the bottom of the homepage) and 2) without a submit button if possible.
Here is the php code:
<form name="test" action="<?php echo
htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<select name="county" id="select13">
<option value="All">All</option>
<option value="County1">County1</option>
<option value="County_2">County 2</option>
...
</select>
<input type="submit" name="submit" value="Set County">
</form>
<?php
if(isset($_POST['submit']))
{
$county = $_POST['county'];
$www = "http://www.website.com/";
$food = "/topics/Food/programs.aspx";
$meals = "/topics/Meals/programs.aspx";
....
echo "<a href=$www/$county/$food>Food</a><br>";
echo "<a href=$www/$county/$meals>Meals</a><br>";
The above code works fine, but requires a page refresh. I was attempting to use jquery to just take a list of links, such as:
Food
And just replace "county" with the value from a dropdown box.
function changelinks(){
var countyvals = $("#county").val();
$("a[href^='http://www.webpage.com/topics/']")
.each(function(){
this.href = this.href.replace(/^http:\/\/www\.webpage\.com\/topics\//,"http://www.webpage.com/topics/"+countyvals);
});}
The above code works fine changing the link once, but after the link is changed I can't target the links anymore. I just started teaching myself jquery today, so I've no idea where to look for a better solution.
What might be the best way of changing these links?
Should I try some ajax on the php code, or is there a better/simpler solution through jquery?
THANKS!
I would use HTML 5 data attributes. Have a data-relativeurl attribute on each anchor of interest, then you can use
function changelinks(){
var countyvals = $("#selector13").val();
$("a[href^='http://www.webpage.com/topics/']")
.each(function(){
this.href = "http://www.webpage.com/" + countyvals + $(this).attr('data-relativeurl');
});}
I have several questions regarding forms and PHP but if I should put them into different posts then I will.
Here is my form code:
<form id="t-form" name="tForm" action="translate.php" method="POST">
<div id="t-bar">
<div class="t-select">
<select name="start-lang" id="choice-button">
<option value="english">English</option>
</select>
<label>into</label>
<select name="end-lang" id="choice-button" onChange="document.forms['tForm'].submit();">
<option value="caps"<?php if ($resLang == 'caps') echo ' selected="selected"'; ?>>CAPS</option>
<option value="lowercase"<?php if ($resLang == 'lowercase') echo ' selected="selected"'; ?>>lowercase</option>
</select>
<input type="submit" id="t-submit" value="Translate">
</div>
</div>
<div id="t-main">
<textarea id="txt-source" name="t-src" autofocus="autofocus" placeholder="Type in what you would like to convert…" onChange="document.forms['tForm'].submit();"><?php echo $source; ?></textarea>
<input type="button" id="t-clear" onclick="this.form.elements['t-src'].value=''">
<textarea id="txt-result" name="txt-result" readonly disabled="disabled" placeholder="result..."><?php echo $result; ?></textarea>
<input type="button" id="t-copy" name="t-copy">
</div>
</form>
Question 1: I currently have onclick="this.form.elements['t-src'].value=''" which clears one textbox when the button is pressed. Is it possible to have the same attribute clear both textareas in my form? I can't seem to find an answer anywhere for clearing 2 elements with 1 button. I do not want to clear the form as I would like to keep the selected dropdown values so that is why I'm doing it this way.
Question 2: How would I go about implementing a live refresh of the results textarea so they user can simply type and see the result? I've look at the ajax and jquery required and am confused as most don't show how to output to a form element and only to a div. (Similar to google's translate)
Question 3: I realized that if a user does a new line in the textarea, when they submit for translate, it gives them a php header error. Any ideas how I can avoid this? This is my header for the translate.php file used in the form:
header("location: /?txt-result=$result&t-src=$textSource&end-lang=$outputLang");
I am merely trying to do this as a learning excersise and would really appreciate any guidance or answers to the three questions. Many thanks for your help!
question 1
you should have:
onclick="clearTextboxes();"
and in javascript something like:
//if you want to delete all the inputs that are of type text
function clearTextboxes(){
var inputs = document.getElementById('t-form').getElementsByTagName('input');
for (var control in inputs){
if(inputs[control].getAttribute('type') == 'text'){
inputs[control].value = '';
}
}
}
question 2
it is far too broad to put here as an answer, you should really look at jQuery's $.ajax, and create a different question with specific doubts.
question 3
use the PHP urlencode() function
Answer 1: Have your onclick event call a function which clears those values for you:
<script type="text/JavaScript">
function clearTextareas()
{
this.form.elements["t-src"].value = "";
this.form.elements["txt-result"].value = "";
}
</script>
<input type="button" id="t-clear" onclick="clearTextareas()">
Answer 2: Add an onkeydown event in the source textarea that peforms the translation (or whatever it needs to do) and then puts the result in the result textarea:
<script type="text/JavaScript">
function translateText()
{
var text = this.form.elements["t-src"].value;
// do something
this.form.elements["txt-result"].value = text;
}
</script>
<textarea id="txt-source" name="t-src" autofocus="autofocus" placeholder="Type in what you would like to convert…" onkeydown="translateText()"><?php echo $source; ?></textarea>
Answer 3: Perhaps an onsubmit event in the form element that will sanitize the input from the text area. Have a look at JavaScript's encodeURIComponent. Perhaps this will work for you:
<script type="text/JavaScript">
function sanitize()
{
this.form.elements["t-src"].value = encodeURIComponent(this.form.elements["t-src"].value);
}
</script>
any help would be great. Here's what I have so far:
PHP:
<?php
$arr1 = array("1080", "939", "769", "696","572", "498", "408", "369");
$arr2 = array("1275", "1095", "890", "799", "676", "580", "472", "423");
?>
PullDown Menu:
<select name="age" id="age">
<option value="<?php echo $arr1[0]; ?>">18-24</option>
<option value="<?php echo $arr2[0]; ?>">25-29</option>
</select>
Textfield:
<input name="planA" type="text" id="planA" value="<?php echo $arr1[0]; ?>" size="10" />
I need the textfield to show the correct value from the array, based on what I choose from the pulldown menu.
Thx.
When a user selects a value from the pulldown, they'll just see what you have between option tags; so for the second value, 25-29 would be displayed. According to your code, this has a corresponding value of 1275. If that's the value you need to populate in a text box, you could do so using Javascript:
<select name="age" id="age" onChange=PopulateField(this.value);>
...
And in the head of the document:
<script type="text/javascript" language="javascript">
function PopulateField(numValue)
{
document.getElementById('planA').value = numValue;
}
</script>
Of course realize that if Javascript is disabled on the user's browser, this won't work. When the form is submitted, you'll still be able to get the value of course, by working with the age variable; its value already is set to the element from the array. (I assume the text box is just for user feedback.)
Now, if the form is already submitted, and you want to show the results of the submission in the text field, then all you need to do is change your PHP code to reflect the selected value as so:
<input name="planA" type="text" id="planA" value="<?php echo $_POST['age']; ?>" size="10" />
If your form uses GET instead of POST, change $_POST to $_GET accordingly.
Edit (per comments):
If you have multiple textboxes to populate, it kind of depends whether you have just one pulldown menu to trigger them, or if there are multiple pulldown menus. I'll assume you have another pulldown menu to populate another textbox. In that case, you can use a second javascript function like this:
<script type="text/javascript" language="javascript">
function PopulateFieldA(numValue)
{
document.getElementById('planA').value = numValue;
}
function PopulateFieldB(numValue)
{
document.getElementById('planB').value = numValue;
}
</script>
On the pulldown that is associated with the textfield for plan B, use the appropriate onChange event:
<select name="ageB" id="ageB" onChange=PopulateFieldB(this.value);>
You could pass multiple arguments to a function so you could populate multiple boxes:
function PopulateFields(numValueA, numValueB)
{
document.getElementById('planA').value = numValueA;
document.getElementById('planB').value = numValueB;
}
Anything else is just speculation on my part because I don't really know the specifics of your application. Hopefully this helps set you on the right track.