After a bit of help and learning, I have managed to change a target via JScript, but I can't seem to figure out how to make a variable or make it do a calculation.
My code so far is (these are three Form Boxes + a Submit Button):
NUMBER
<input name="contact_build"
type="text"
id="contact_build"
value="<?php echo $row_contact['contact_build']; ?>" />
TYPE
<select id="contact_type"
name="contact_type"
onchange="targ.value=this.value" />
<?php
$specresult = mysql_query("SELECT * FROM `types` ORDER BY type_value");
while ($specrow = mysql_fetch_array($specresult)) {
echo '<option value="' . $specrow['type_name'] . '">' . $specrow['type_name'] . '</option>';
}
?>
</select>
VALUE
<input name="contact_value" id="targ" value="<?php
$var1 = $row_contact['contact_build'];
$var2 = $row_value['type_value'];
$total = round($var2 * $var1);
echo "" . $total . "";
?>" />
<input type="submit" name="Submit2" value="Update" />
What I want to do is make "TARG" the "$VAR2" variable, so that it can work out the VALUE calculation then echo (or what ever command is required) the answer in the VALUE box, as soon as the user changes the option in the TYPE box. Hope this makes sense.
At the moment I have managed to get it to show the "TYPE" value in the "VALUE" box. It ignores any "echo" command above.
Am I looking at this incorrectly and it should be done another way?
PS: I know it's MYSQL; I am working on learning PDO as we speak to change it over. :-) But for the moment, I just want to figure this out using the language that I have basic knowledge of.
Go through the code below.
<body>
<input name="contact_build"
type="text"
id="contact_build"
value="<?php echo $row_contact['contact_build']; ?>" />
<select onchange="change(this.value)" >
<option value="1"> 1</option>
<option value="2"> 2</option>
<option value="3"> 3</option>
</select>
<input type="text" id="targ" value="2"/>
<script>
function change(val) {
var cnt_bld = document.getElementById("contact_build").value;
var total_val = Math.round(parseInt(val) * parseInt(cnt_bld));
document.getElementById("targ").value = total_val;
}
</script>
</body>
In the above code i have called a function change(this.value) which will accept the select box value. Then in the function I have used that value to change the value of input field. Look at document.getElementById. With your code your were directly using a id instead. Hope this helps.
EDIT
this line
echo '<option value="' . $specrow['type_name'] . '">' . $specrow['type_name'] . '</option>';
can be done like this if you have those name and value.
echo '<option value="' . $specrow['type_value'] . '">' . $specrow['type_name'] . '</option>';
assuming your another column name as type_value where values are stored like 100,200and so on and type_name is the name like good, better or best.
Hope this is what you may want
<html>
<body>
<input name="contact_build"
type="text"
id="contact_build"
value="10" />
<select onchange="change(this.value)" >
<option value="0">Select</option>
<option value="1"> 1</option>
<option value="2"> 2</option>
<option value="3"> 3</option>
</select>
<input type="text" id="targ" value="0"/>
<script>
function change(val) {
document.getElementById("targ").value = document.getElementById("contact_build").value*val;
}
</script>
</body>
</html>
Related
I know this question has been asked a lot of times in several other ways but none of them helped me. So, I have formatted it in my own words.
Supppose I have a select box like this:
<select name="something">
<option value="1"><?php echo $value1; ?> for <?php echo $value2; ?>
</select>
<input type="text" name="sometext" value="">
I want to have the <?php echo $value1; ?> in the text field updated live on change of the select box option. To be clear, I DO NOT want the value="1" in the text field and I need to have that value="1" there for some reason and I cannot replace it with value="<?php echo $value1; ?>". I strictly want the inside value <?php echo $value1; ?> to be replaced in the text field. But I do not know how I can achieve it. Please help me experts. For live changing jQuery preferred.
Try below code:
<select name="something">
<option value="1" data="<?php echo $value1; ?>"><?php echo $value1; ?> for <?php echo $value2; ?></option>
</select>
<input type="text" name="sometext" value="">
See below working HTML
jQuery(document).ready(function($){
$('#something').change(function(){
$('#sometext').val($(this).find(':selected').attr('data'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="something" id="something">
<option value="1" data="value1">value1 form value01</option>
<option value="1" data="value2">value2 form value02</option>
<option value="1" data="value3">value3 form value03</option>
<option value="1" data="value4">value4 form value04</option>
</select>
<input type="text" name="sometext" id="sometext" value="">
Hope this will work for you,
$(document).ready(function() {
$('select').change(function(){
var selectedOption = $("select option:selected").text(); //Get the text
selectedOption = selectedOption.split("for"); //split the 2 value by using for
alert(selectedOption[0]); //Get the value before for
$('input').val(selectedOption[0]);
});
});
You need to fetch the selected option text instead of the usual option value, it is pretty easy to do.
You don't need to add any data attributes to achieve this, as there is a method to fetch the actual option text.
Here is a working example:
PHP for populating a select element (below I show the static HTML)
<select id="something" name="something">
<?php foreach($selectList as $value=>$text){ ?>
<option value="<?php echo $value;?>"> <?php echo $text;?> </option>
<?php } ?>
</select>
HTML
<select id="something" name="something">
<option value="1"> Value 1 </option>
<option value="2"> Value 2 </option>
<option value="3"> Value 3 </option>
</select>
<input type="text" id="sometext" name="sometext" value=""/>
jQuery
$(document).ready(function(){
$('#something').on('change',function(){
var selectedText = $(this).children(':selected').text();
$('#sometext').val(selectedText);
});
});
This approach is fast and easy to maintain.
And of course a jsfiddle to see it in action: https://jsfiddle.net/kzgapkt5
Hope it helps a bit
I have using the following code for my dropdown
<select class="form-control" name="device" id="device" onChange="getBrand(this.value);">
<option selected name="device" id="device" value="<?php echo $row['id'] ?>"><?php echo $row['name']; ?></option>
</select>
for form submit, i have used this code
if(isset($_POST['submit'])){
extract($_POST);
$device = $_POST['device'];
}
I want to get selected value in button submit, currently I got the id instead of value.
Thanks in advance.
You have to put $row['name'] as value of your option
<select class="form-control" name="device" id="device" onChange="getBrand(this.value);">
<option selected name="device" id="device" value="<?php echo $row['name'] ?>"><?php echo $row['name']; ?></option>
</select>
If you can't change option value, you could use jQuery:
$("#your_form").submit( function () {
var option_text = $('#device').find(":selected").text();
$("#your_form").append('<input name="selected_option_text" type="hidden" value="' + option_text + '">');
});
This will add a input field with name "selected_option_text" before submit. So you will find it in your receiving script
You can add a data-attribute on your option
for example
data-value = $row['name']
Then get the data-attr in your Javascript/jQuery
Is there a way to get the previous value of select option?
the previous value is Red
If i change it to green it will echo the selected color
How can i echo the previous color which is red?
this is my code : thanks :)
<form action="#" method="post">
<select name="Color">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
<option value="Pink">Pink</option>
<option value="Yellow">Yellow</option>
</select>
<input type="submit" name="submit" value="Get Selected Values" />
</form>
<?php
if(isset($_POST['submit'])){
$selected_val = $_POST['Color'];
echo "You have selected :" .$selected_val . "<p>";
echo "The previous value is :" ;
}
?>
Use hidden field to store current value. On form post, check if the current value is different than selected value show it.
Pro tip: Always encrypt your hidden field data
store the previous value in your form as hidden value and get it
<?php
if(isset($_POST['submit'])){
$selected_val = $_POST['Color'];
$previous = $_POST['previous'];
}
?>
<form action="#" method="post">
<select name="Color">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
<option value="Pink">Pink</option>
<option value="Yellow">Yellow</option>
</select>
<input type="hidden" name="previous" value="<?php echo $selected_val; ?>"/>
<input type="submit" name="submit" value="Get Selected Values" />
</form>
<?php echo "You have selected :" .$selected_val . "<p>";
echo "The previous value is :".$previous ; ?>
Since you must never trust user submitted content, another way is to build your form from PHP and do the test on the server side.
Example:
<?php
$colors = Array('Red', 'Green', 'Blue', 'Pink', 'Yellow');
?>
<form method="POST">
<select name="Color"><?php
foreach($colors as $color)
{
printf(' <option value="%1$s">%1$s</option>'."\n", $color);
}
?>
</select>
<input type="submit">
</form>
<?php
if (!empty($_POST['Color']))
{
$previous_index = array_search($_POST['Color'], $colors) - 1;
// wrap around if the color is the first
if ($previous_index < 0) {
$previous_index = count($colors);
}
printf(
"You have selected <q>%s</q>, the previous value is: %s\n",
$_POST['Color'],
$colors[ $previous_index ]
);
}
?>
The code is obviously longer than it could for educative purpose.
Here is another solution using jQuery, as a bonus you keep track of whole history and not just previous selection.
I have not tested the PHP part, but you get the idea.
HTML
<form action="#" method="post">
<select name="Color" onChange="updateHistory(this);">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
<option value="Pink">Pink</option>
<option value="Yellow">Yellow</option>
</select>
<input type="hidden" id="history" name="history" value="">
</div>
</div>
<input type="submit" name="submit" value="Get Selected Values" />
</form>
<?php
if(isset($_POST['submit'])){
$selected_val = $_POST['Color'];
$hist = explode(',',$_POST['history']);
// pop the last value, which is current selection
array_pop($hist);
// get the last value, which now is previous
$last_valaue = end($hist);
echo "You have selected :" .$selected_val . "<p>";
echo "The previous value is :" . $last_valaue ;
echo 'DEBUG:<br>';
var_dump($hist);
}
?>
JS
function updateHistory(el){
var val = $(el).val();
var hist = $('#history').val();
if (hist.length > 0) {hist += ','}
hist += val;
$('#history').val(hist);
}
Example JS Fiddle
UPDATE 1:
You can further manipulate history array in PHP to your needs, for example, if you need unique values, you can use array_unique() (http://php.net/manual/en/function.array-unique.php)
I am having an issue with a table where each cell contains an id'd input or select field. The cell contents are dynamically generated from a MySQL query. Everything works fine except for my dynamically generated SELECT drop downs. I am using the following code in a switch statement:
case 'crew_1':
case 'crew_2':
echo '<td><select class="'.classExt($types[$key]).' '. $key .'_c" id="' . $key . '--' . $idx .'">';
echo '<option value="" selected="selected"></option>';
while ($rowtech = mysqli_fetch_assoc($rtech)){
echo '<option value="' . $rowtech['name'] . '">' . $rowtech['name'] . '</option>';
} mysqli_data_seek($rtech,0);
echo '<option value="TEST">TEST</option>';
echo '</select></td>'; break;
This creates the following HTML:
<td>
<select class="varchar crew_1_c" id="crew_1--1">
<option value="" selected="selected"></option>
<option value="Name 1">Name 1</option>
<option value="Name 2">Name 2</option>
<option value="TEST">TEST</option>
</select>
</td>
From this I can select the blank or 'TEST' option and it returns the correct value in a console.log, but if I choose one of the dynamically generated names, the box returns back to the default blank value. I get the same responses on Chrome and IE.
Where is my disconnect?
Included for the person requesting the script generating to output to console:
$('tbody select, tbody input').change(function(){
console.log($(this).val());
});
OP, you're missing the name attribute.
This works fine for me:
<form method="post" action="">
<select class="varchar crew_1_c" id="crew_1:1" name="choice">
<option value="" selected="selected"></option>
<option value="Name 1">Name 1</option>
<option value="Name 2">Name 2</option>
<option value="TEST">TEST</option>
</select>
<input type="submit" value="Submit" name="submit" />
</form>
<?php
var_dump($_REQUEST);
?>
Found my issue. The JS request earlier had me dig back through my code to discover that I was setting my values toUpperCase() for submission for consistency, but that was breaking my value match on the drop down. I set my values to uppercase in the select options also and TA-DA!
Thanks for the help, guys. Sometimes it takes a fresh pair of eyes to point out the obvious.
This question already has answers here:
Using $_POST to get select option value from HTML
(8 answers)
Closed 6 years ago.
I am trying to get the option selected using PHP, but I ran out of ideas!
Below is the code I have tried until now:
<select>
<option value="1">Yes</options>
<option value="2">No</options>
<option value="3">Fine</options>
</select>
<input type="text" value="" name="name">
<input type="submit" value="go" name="go">
So, what do I have to do?
Programmers are lazy...er....efficient....I'd do it like so:
<select><?php
$the_key = 1; // or whatever you want
foreach(array(
1 => 'Yes',
2 => 'No',
3 => 'Fine',
) as $key => $val){
?><option value="<?php echo $key; ?>"<?php
if($key==$the_key)echo ' selected="selected"';
?>><?php echo $val; ?></option><?php
}
?></select>
<input type="text" value="" name="name">
<input type="submit" value="go" name="go">
<select>
<option value="1" <?php if ($myVar==1) echo 'selected="selected"';?>>Yes</options>
<option value="2" <?php if ($myVar==2) echo 'selected="selected"';?>>No</options>
<option value="3" <?php if ($myVar==3) echo 'selected="selected"';?>>Fine</options>
</select>
<input type="text" value="" name="name">
<input type="submit" value="go" name="go">
This is a very simple and straightforward way, if I understand your question correctly.
you can use this..
<select name="select_name">
<option value="1"<?php echo(isset($_POST['select_name'])&&($_POST['select_name']=='1')?' selected="selected"':'');?>>Yes</option>
<option value="2"<?php echo(isset($_POST['select_name'])&&($_POST['select_name']=='2')?' selected="selected"':'');?>>No</option>
<option value="3"<?php echo(isset($_POST['select_name'])&&($_POST['select_name']=='3')?' selected="selected"':'');?>>Fine</option>
</select>
First of all give a name to your select. Then do:
<select name="my_select">
<option value="1" <?= ($_POST['my_select'] == "1")? "selected":"";?>>Yes</options>
<option value="2" <?= ($_POST['my_select'] == "2")? "selected":"";?>>No</options>
<option value="3" <?= ($_POST['my_select'] == "3")? "selected":"";?>>Fine</options>
</select>
What that does is check if what was selected is the same for each and when its found echo "selected".
I suppose that you are using an array to create your select form input.
In that case, use an array:
<?php
$selected = array( $_REQUEST['yesnofine'] => 'selected="selected"' );
$fields = array(1 => 'Yes', 2 => 'No', 3 => 'Fine');
?>
<select name=‘yesnofine'>
<?php foreach ($fields as $k => $v): ?>
<option value="<?php echo $k;?>" <?php #print($selected[$k]);?>><?php echo $v;?></options>
<?php endforeach; ?>
</select>
If not, you may just unroll the above loop, and still use an array.
<option value="1" <?php #print($selected[$k]);?>>Yes</options>
<option value="2" <?php #print($selected[$k]);?>>No</options>
<option value="3" <?php #print($selected[$k]);?>>Fine</options>
Notes that I don't know:
how you are naming your input, so I made up a name for it.
which way you are handling your form input on server side, I used $_REQUEST,
You will have to adapt the code to match requirements of the framework you are using, if any.
Also, it is customary in many frameworks to use the alternative syntax in view dedicated scripts.
I use inline if's
($_POST['category'] == $data['id'] ? 'selected="selected"' : false)
I have 2 php files and i made this, and it works.
(this is an example) the first code is from the one file and the second code from two file.
<form action="two.php" method="post">
<input type="submit" class="button" value="submit" name="one"/>
<select name="numbers">
<option value="1"> 1 </option>
<option value="2"> 2 </option>
<option value="3"> 3 </option>
</select>
</form>
if(isset ($_POST['one']))
{
if($_POST['numbers']=='1')
{
$a='1' ;
}
else if($_POST['numbers']=='2')
{
$a='2' ;
{
else if ($_POST['numbers']=='3')
{
$a='3' ;
}
}
This answer is not relevant for particular recepient, but maybe useful for others.
I had similiar issue with 'selecting' right 'option' by value returned from database.
I solved it by adding additional tag with applied display:none.
<?php
$status = "NOT_ON_LIST";
$text = "<html>
<head>
</head>
<body>
<select id=\"statuses\">
<option value=\"status\" selected=\"selected\" style=\"display:none\">$status</option>
<option value=\"status\">OK</option>
<option value=\"status\">DOWN</option>
<option value=\"status\">UNKNOWN</option>
</select>
</body>
</html>";
print $text;
?>
This is the solution that I've came up with:
<form name = "form1" id = "form1" action = "#" method = "post">
<select name = "DropDownList1" id = "DropDownList1">
<?php
$arr = array('Yes', 'No', 'Fine' ); // create array so looping is easier
for( $i = 1; $i <= 3; $i++ ) // loop starts at first value and ends at last value
{
$selected = ''; // keep selected at nothing
if( isset( $_POST['go'] ) ) // check if form was submitted
{
if( $_POST['DropDownList1'] == $i ) // if the value of the dropdownlist is equal to the looped variable
{
$selected = 'selected = "selected"'; // if is equal, set selected = "selected"
}
}
// note: if value is not equal, selected stays defaulted to nothing as explained earlier
echo '<option value = "' . $i . '"' . $selected . '>' . $arr[$i] . '</option>'; // echo the option element to the page using the $selected variable
}
?>
</select> <!-- finish the form in html -->
<input type="text" value="" name="name">
<input type="submit" value="go" name="go">
</form>
The code I have works as long as the values are integers in some numeric order ( ascending or descending ). What it does is starts the dropdownlist in html, and adds each option element in php code. It will not work if you have random values though, i.e: 1, 4, 2, 7, 6. Each value must be unique.