how to select a specific option when a condition exists - javascript

I want to select the specific option in drop down list when a condition is existed.I set the Session in php and if the combo box has the value of 1 , it will be shown the option with value 1. I mean if session is 1, select the option with value of 1, if session is 2, select the option with vlaue of 2, and so on... . I want to set automatically select(I see the changes) with session in php.
sth like blewo:
<select id="sel" >
<option value='1'>one</option>
<option value='2'>two</option>
<option value='3'>three</option>
</select>
<?php $_SESSION['num']='1'; ?>
<script>
//must be shown the option with value of `1`.
<script>

Try this .
<select id="sel" >
<option value='1'>one</option>
<option value='2'>two</option>
<option value='3'>three</option>
</select>
<?php $_SESSION['num']='1'; ?>
<script>
//set local variable value so that I don't have to do it for each of the following ways to do this.
var num = "<?php echo $_SESSION['num']; ?>";
//normal javascript
document.getElementById("sel").value = num;
//using jQuery
$("#sel").val(num);
<script>
Or this try vikingmaster's way

You don't necessarily need js to do this. You can simply use php since you're already grabbing the num from the session.
Easiest way to do it would be:
<select id="sel" >
<?php if($_SESSION['num'] == 1): ?>
<option value='1' selected>one</option>
<?php else: ?>
<option value='1'>one</option>
<?php endif; ?>
<option value='2'>two</option>
<option value='3'>three</option>
</select>
But if you want to use javascript(jQuery in particular here), you can do something like this:
<script>
$(document).ready(function(){
var num = <?php echo $_SESSION['num']; ?>;
$('#sel > option').each(function(){
if($(this).val() == num){
$(this).prop('selected', true);
}
});
});
</script>
Here's a fiddle.
There are a lot of ways to do this. This is what approach I would take, I'm sure others can provide just as viable or probably better answers.

Just set the value with the selected attribute
<select id="sel" >
<option value='1' selected>one</option>
<option value='2'>two</option>
<option value='3'>three</option>
</select>
<?php $_SESSION['num']='1'; ?>
<script>
//alternately, set it explicitly
var element = document.getElementById('sel');
element.value = 1;
<script>

<select id="sel" >
<option value='1' <?php if($_SESSION['num']=='1') echo "selected"; ?> >one</option>
<option value='2' <?php if($_SESSION['num']=='2') echo "selected"; ?> >two</option>
<option value='3' <?php if($_SESSION['num']=='3') echo "selected"; ?> >three</option>
</select>

Related

Quick Edit Menu add new dropdown with selected on current post [duplicate]

Typically when you need to select an item by default, you do:
<select>
<option value="1"> Volvo </option>
<option value="2" selected="true"> Saab </option>
<option value="3"> Mercedes </option>
<option value="4"> Audi </option>
</select>
Is it possible to get something like this?
<select selectedValue="2">
<option value="1"> Volvo </option>
<option value="2"> Saab </option>
<option value="3"> Mercedes </option>
<option value="4"> Audi </option>
</select>
It works out easier in PHP since you only have to soft-code one value, instead of handling the selected attribute on any possible <option/>.
There is no attribute like that on the <select> element. Assuming your <option> output is in a loop, I don't see how it makes a huge difference:
$selected = "2";
foreach($values as $key => $val) {
echo "<option value=\"" . $key . "\"" . ($key == $selected ? " selected=\"selected\">" : ">") . $val . "</option>";
}
(my PHP is a little rusty, that may not be 100% correct)
No, but you can add your default value to your id like
<select id="default-value-2">
then in your options, you have
<option value="2" <?php echo is_this_the_default_value ? selected='true' : '' ?>
or something to that effect(forgive me i forgot my php syntax, but i hope you get the point).
Anyway, that is a dirty fix also, so i suggest just adding a method to check for the default selected tag and printing it selected="selected" when it is the default. You can just call it once if you loop through your select options
Put JavaScript after the declaration of the listbox and set the selected index there:
<script>
document.getElementById('listBoxId').selectedIndex=<?php echo $INDEX ?>;
</script>
Something like this.
You can do it like this:
$value = 1;
<select>
<?php if($value==1) echo "<option selected='true'> Volvo </option>";
else echo "<option> Volvo </option>"; ?>
<?php if($value==2) echo "<option selected='true'> Saab </option>";
else echo "<option> Saab </option>"; ?>
</select>
PHP:
<select>
<option value="1" <?php echo ($row['status']==1) ? 'selected' : '' ?>>Permitido</option>
<option value="2" <?php echo ($row['status']==2) ? 'selected' : '' ?>>Bloqueado</option>
</select>
I found myself googling this to see if there was a better way to do it.
The best and cleanest answer is from #roryf, however if you are not looping through your data I thought it would be a lot cleaner to wrap it up in a function:
function set_selected($desired_value, $new_value)
{
if($desired_value==$new_value)
{
echo ' selected="selected"';
}
}
Then you would use it like this:
<?php $selected_value = 2; ?>
<select>
<option value="1"<?php set_selected('1', $selected_value); ?>> Volvo </option>
<option value="2"<?php set_selected('2', $selected_value); ?>> Saab </option>
<option value="3"<?php set_selected('3', $selected_value); ?>> Mercedes </option>
<option value="4"<?php set_selected('4', $selected_value); ?>> Audi </option>
</select>
This would set Saab as selected :)
Preload $statusid from DB then -> (i have to escape ")
PHP:
$option_0 = '';
$option_11 = '';
$option_12 = '';
$option_13 = '';
$option_14 = '';
$option_15 = '';
$option_16 = '';
if ($statusid ==0 ){
$option_0 = 'selected=\"\"';
}elseif($statusid ==11 ){
$option_11 = 'selected=\"\"';
}elseif($statusid ==12 ){
$option_12 = 'selected=\"\"';
}elseif($statusid ==13 ){
$option_13 = 'selected=\"\"';
}elseif($statusid ==14 ){
$option_14 = 'selected=\"\"';
}elseif($statusid ==15 ){
$option_15 = 'selected=\"\"';
}elseif($statusid ==16 ){
$option_16 = 'selected=\"\"';
}
HTML:
."<select id=\"id\" name=\"name\" >"
." <option {$option_0} value=\"0\">...TEXT...</option>"
." <option {$option_11} value=\"11\">TEXT</option>"
." <option {$option_12} value=\"12\">TEXT</option>"
." <option {$option_13} value=\"13\">TEXT</option>"
." <option {$option_14} value=\"14\">TEXT</option>"
." <option {$option_15} value=\"15\">TEXT</option>"
." <option {$option_16} value=\"16\">TEXT</option>"
."</select><br /><br />"
work Perfect for me.

how to avoid repetition of values in dropdown list while updating in php

I want to update "profile of a user" in php. There is a repetition of one value for two times in dropdown list. for example i take language value='Punjabi' from database but there is also a value placed in dropdown with name of 'Punjabi'.
The issue is simply that there is a repetition of value which i don't want.
<?php $result=mysqli_query($conn, "select * from profile where id=$firstPerson");
while($queryArray=mysqli_fetch_array($result)){ ?>
<select name="language" id="language" >
<option value='<?php echo $queryArray["language"];?> '> <?php echo $queryArray["language"]; ?></option>
//for example, the value from database is "Punjabi"
<option value="Hindi">Hindi</option>
<option value="Punjabi">Punjabi</option>
<option value="Urdu">Urdu</option>
</select>
<?php } ?>
when a value='Punjabi' from database is selected in dropdown list, the dropdown should not show the value='Punjabi' that is already placed in dropdown.
Remember: i have more than 1000 values in my dropdown(html) list.
screenshot
Instead of creating a new option according to the user data, Check if existing options are equal to user data:
<select name="language" id="language" >
<option value="Punjabi" <?php if ($queryArray["language"]=="Punjabi"){echo 'selected="selected"'} ?>>Punjabi</option>
<option value="Hindi" <?php if ($queryArray["language"]=="Hindi"){echo 'selected="selected"'} ?>>Hindi</option>
<option value="Urdu" <?php if ($queryArray["language"]=="Urdu"){echo 'selected="selected"'} ?>>Urdu</option>
</select>
If there are large number of options and you don't want to hard code these conditions, you can remove the second option using javascript on DOM ready:
$(document).ready(function(){
$('option[value="<?php echo $queryArray["language"] ?>"]').eq(1).remove();
})
skip the loop when value is equal to Punjabi, Urdu and Hindi.
<?php $result=mysqli_query($conn, "select * from profile where id=$firstPerson");
while($queryArray=mysqli_fetch_array($result)){ ?>
<select name="language" id="language" >
<?php if($queryArray["language"]!="Punjabi" && $queryArray["language"]!="Urdu" &&
$queryArray["language"]!="Hindi") { ?>
<option value="Hindi">Hindi</option>
<option value="Punjabi">Punjabi</option>
<option value="Urdu">Urdu</option>
<?php } ?>
I think you are doing it wrong way the correct way would be having a table which stored all the languages along with values
using selected attribute to achieve your objective
<?php
$result=mysqli_query($conn, "select * from profile where id=$firstPerson");
$queryArray1=mysqli_fetch_array($result);
$langOfUser=$queryArray1["language"];
?>
<select name="language" id="language" >
<?php $result=mysqli_query($conn, "select * from langtab");
while($queryArray=mysqli_fetch_array($result)){ ?>
<option value='<?php echo $queryArray["languageValue"];?> ' <?php if($langOfUser== $queryArray["languageValue"]){ echo 'selected';}?>> <?php echo $queryArray["languageName"]; ?></option>
<?php } ?>
</select>
You have to use if condition to display values in select option.
<select name="language" id="language" >
<?php $result=mysqli_query($conn, "select * from profile where id=$firstPerson");
while($queryArray=mysqli_fetch_array($result)){
if($queryArray["language"]!="Punjabi") {
$opval = "<option value=" . $queryArray["language"] . ">". $queryArray["language"]. " </option> "
echo $opval;
}
?>
<option value="Punjabi">Punjabi</option>
<option value="Hindi">Hindi</option>
<option value="Urdu">Urdu</option>
</select>
So your problem is that you have html hardcoded options and database options. You need to merge them into one on that website.
So you can use some javascript
elements = [1, 2, 9, 15].join(',')
$.post('post.php', {elements: elements})
But you can fill your elements like this is you don´t want to write it by hand
$("#id select").each(function()
{
allOptionsInSelect.push($(this).val());
});
Than on php side you can do
$elements = $_POST['elements'];
$elements = explode(',', $elements);
And now you have html hardcoded select on server side. Now you need to check if it doesn´t already exist when you are printing from database
You can do that like this
if(in_array(value_from_database, $elements) {
// It is so skip
} else {
// It is not, so print it
}
You can use if elseif this way.
<select name="language" id="language" >
<option value='<?php echo $queryArray["language"];?>'><?php echo $queryArray["language"]; ?></option>
<?php if ($queryArray["language"] == "Hindi") { ?>
<option value="Punjabi">Punjabi</option>
<option value="Urdu">Urdu</option>
<?php } elseif ($queryArray["language"] == "Urdu") { ?>
<option value="Punjabi">Punjabi</option>
<option value="Hindi">Hindi</option>
<?php } elseif ($queryArray["language"] == "Punjabi") { ?>
<option value="Urdu">Urdu</option>
<option value="Hindi">Hindi</option>
<?php } ?>

Changing the select value in php

I’m making an interface with 2 select lists that are interconnected with each other, so what I want is:
If the user selects an option in the category dropbox the second select list will show all the options in that category.
<hmtl>
<label>Section</label>
<select class="form-control selcls" name="txtsection" id="txtsection" >
<?php
while ($rows = mysqli_fetch_array($queryResultsec)) { ?>
<option value="<?php echo $rows['Gradelvl_ID'];?>"><?php echo
$rows['Section_Name'];?></option>
<?php }
?>
</select>
<label>Section</label>
<select class="form-control selcls" name="txtsection" id="txtsection" >
<?php
while ($rows = mysqli_fetch_array($queryResultsec)) {?>
<option value="<?php echo $rows['Gradelvl_ID'];?>"><?php echo
$rows['Section_Name'];?></option> <?php }
?>
</select>
</hmtl>
I took some to write some code according to your problem. While writing this, I assumed that you have a relationship between the two tables where you have stored the categories and the options. I assumed that the relationship is using "Gradelvl_ID". I also assume that you have some knowledge in JavaScript, jQuery, and AJAX.
Based on that, I created the code below.
This would be your selection area.
<hmtl>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
</head>
<body>
<label>Section</label>
<select class="form-control selcls" name="txtsection" id="cat" >
<?php
while ($rows = mysqli_fetch_array($queryResultsec)) { ?>
<option id="<?php echo $rows['Gradelvl_ID'];?>"><?php echo $rows['Section_Name'];?></option>
<?php } ?>
</select>
<label>Section</label>
<select class="form-control selcls" name="txtsection" id="options" ></select>
</body>
</html>
This script is using jQuery, so you need to link the jQuery library to you above page. Also you can have this script inside the first page using <script></script> tags or attached as a .js file separately.
$(document).ready(function(){
$(document).on('change', '#cat', function(){
$.ajax({
url: 'getOptions.php',
type: 'get',
data: {
catId: $(this).prop('id')
}
}).then(function (response) {
$('#options').html(response);
});
});
})
The code above will send the selected ID to the getOptions.php which will contain the PHPto select all the options according to the sent ID number from you options table. Then, if the selection is successful, it will send the data back which will be captured by the AJAX code above and draw the options inside the second drop down.
<?php
include_once('dbconnect.php');
//I'm not a big mysqli user
if(!empty($_GET["id"])){
$results = $conn -> prepare("SELECT * FROM <your table name> WHERE id = ?");
$results -> bind_param('i', $_GET["id"]);
$results -> execute();
$rowNum = $results -> num_rows;
if ($rowNum > 0){
while($optRows = $results -> fetch_assoc()){ ?>
<option id="<?php echo $rows['Gradelvl_ID'];?>"><?php echo $rows['Section_Name'];?></option>
<?php
}
}
}?>
Also, pay attention to the code above. I'm using prepared statements, which is a very good habit to get into. Look it up here.
As I said, I was assuming some part of the code and used the information given by you, and I hope you do some more research and make the code above work for you.
Try This Code:
$("#select1").change(function() {
if ($(this).data('options') === undefined) {
/*Taking an array of all options-2 and kind of embedding it on the select1*/
$(this).data('options', $('#select2 option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[value=' + id + ']');
$('#select2').html(options);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<select name="select1" id="select1">
<option value="1">Fruit</option>
<option value="2">Animal</option>
<option value="3">Bird</option>
<option value="4">Car</option>
</select>
<select name="select2" id="select2">
<option value="1">Banana</option>
<option value="1">Apple</option>
<option value="1">Orange</option>
<option value="2">Wolf</option>
<option value="2">Fox</option>
<option value="2">Bear</option>
<option value="3">Eagle</option>
<option value="3">Hawk</option>
<option value="4">BWM<option>
</select>
Do one thing
1-Keep your second dropdown empty.
2-Call jquery ajax to get the first dropdown value on change
create a new page where only db connection is defied after that process the sql with respect to the first dropdown selected value
3-get the response to ajax method and get the output

How to change a second select list based on the first select list option when values are dynamic?

I have php page for vehicle search filter which have 2 types of vehicle that is RV's and campervans and also have two selects
<div class="fields">
<p>Vehicle Type</p>
<select class="car" name="car_type" id="car_type">
<option value="0">Select Vehicle</option>
<?php if(count($vehicleType) > 0 ){
foreach($vehicleType as $vt){ ?>
<option value="<?php echo $vt ?>" <?=isset($_GET['car_type'])&&$_GET['car_type']==$vt?'selected':'';?> ><?php echo $vt ?></option>
<?php }
} ?>
</select>
</div>
<div class="fields">
<p>Total No. of Passengers*</p>
<select class="half" name="passengers" id="passengers">
<option>No. of Passengers</option>
<option <?php if(#$_REQUEST['passengers'] == 1){?>selected<?php }?>>1</option>
<option <?php if(#$_REQUEST['passengers'] == 2){?>selected<?php }?>>2</option>
<option <?php if(#$_REQUEST['passengers'] == 3){?>selected<?php } ?>>3</option>
<option <?php if(#$_REQUEST['passengers'] == 4){?>selected<?php }?>>4</option>
<option <?php if(#$_REQUEST['passengers'] == 5){?>selected<?php }?>>5</option>
<option <?php if(#$_REQUEST['passengers'] == 6){?>selected<?php }?>>6</option>
<option <?php if(#$_REQUEST['passengers'] == 7){?>selected<?php }?>>7</option>
<option <?php if(#$_REQUEST['passengers'] == 8){?>selected<?php }?>>8</option>
</select>
</div>
How do I do that with jQuery or php if I choose "Rv" in the first select? The second select would show me 8 passengers . If I choose Campervan in the first select, the second select would show me 5 passengers..
I would probably do something along these lines:
<?php
$number_of_passengers = 8;
if(!empty($_REQUEST['car_type'])) {
$number_of_passengers = $_REQUEST['car_type'] == 'Campervans' ? 5 : 8;
}
$passengers = 0;
if(!empty($_REQUEST['passengers'])){
$passengers = (int) $_REQUEST['passengers'];
}
?>
<select class="car" name="car_type" id="car_type">
<option value="0">Select Vehicle</option>
<option value="RV/Motorhome">RV/Motorhome</option>
<option value="Campervans">Campervans</option>
</select>
<select class="half" name="passengers" id="passengers">
<option>No. of Passengers</option>
<?php
for($i = 1; $i <= $number_of_passengers; $i++) {
?>
<option
<?php
if($i == $passengers) {
echo ' selected ';
}
?>
>
<?php echo $i ?>
</option>
<?php
}
?>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$('#car_type').change(function() {
$("#passengers").children().removeAttr("selected");
if ($(this).val() === 'Campervans') {
$('#passengers option:nth-child(n+7)').hide();
} else {
$('#passengers option').show();
}
});
</script>
There are cleaner ways of doing this but this should serve to get the point across.
Few things to note about the PHP:
See how I check if the $_REQUEST key is available using empty - this avoids having to use # which is generally not a good idea.
I am using a loop to echo the options in the passenger select to avoid code repetition because typing that out 8 times is boring ;-)
Hope this helps!
yes you need to add javascript code for that.
insert below code in your page and check if this is what you want?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$('.car').on('change', function(){
if($(this).val() === 'RV/Motorhome'){
$('.half').find('option').show()
}else if($(this).val() === 'Campervans'){
$('.half').find('option').slice(6).hide();
}
})
</script>

how to change a drop down options to default selected using jquery

Below code is part of my a html form drop down menu:
<div class="wrap-quest-resp" id="fa8">
<div class="input-quest-no-height">FA and port - 8</div>
<div class="input-resp-no-height">
<select id="fa-select-8" name="fa-select-8">
<option disabled="disabled" SELECTED >Dir</option>
<option <?php if ($_POST['fa-select-8']==1) {echo "selected='selected'"; } ?> >1</option>
<option <?php if ($_POST['fa-select-8']==2) {echo "selected='selected'"; } ?> >2</option>
<option <?php if ($_POST['fa-select-8']==3) {echo "selected='selected'"; } ?> >3</option>
<option <?php if ($_POST['fa-select-8']==4) {echo "selected='selected'"; } ?> >4</option>
<option <?php if ($_POST['fa-select-8']==5) {echo "selected='selected'"; } ?> >5</option>
</select>
<select id="proc-select-8" name="proc-select-8">
<option disabled="disabled" SELECTED >Proc</option>
<option <?php if ($_POST['proc-select-8']==a) {echo "selected='selected'"; } ?> >a</option>
<option <?php if ($_POST['proc-select-8']==b) {echo "selected='selected'"; } ?> >b</option>
</select>
<select id="port-select-8" name="port-select-8">
<option disabled="disabled" SELECTED >Port</option>
<option <?php if ($_POST['port-select-8']==0) {echo "selected='selected'"; } ?> >0</option>
<option <?php if ($_POST['port-select-8']==1) {echo "selected='selected'"; } ?> >1</option>
</select>
</div>
</div>
I a using this jquery to hide above mentioned div and its drop down selection
$('#fa8').slideUp("fast");
I would like to change the option selected to its default SELECTED option while hiding the div . That is to below options for all three drop down menus
<option disabled="disabled" SELECTED >Dir</option>
<option disabled="disabled" SELECTED >Proc</option>
<option disabled="disabled" SELECTED >Port</option>
Since you appear to want all of the selects to go to their default values, I'd suggest using this:
$('#fa8').find("select").find("option:first").prop("selected", true);
Depending on how your code is implemented, you could make it part of a callback, as tymeJV suggested, or simply place it on the next line after the slideUp call in the code.
If you use the callback, you can use $(this) instead of $('#fa8'):
$('#fa8').slideUp("fast", function() {
$(this).find("select").find("option:first").prop("selected", true);
});
If you go for the "multi-line" approach, store off the selector for $('#fa8') in a variable, so that you are not running the select twice:
var $wrapReqResp = $('#fa8');
$wrapReqResp.slideUp("fast");
$wrapReqResp.find("select").find("option:first").prop("selected", true);
Use the callback from slideUp and set the 0 index of each to selected via prop()
$('#fa8').slideUp("fast", function() {
//Set the 0 index as selected
$("#fa-select-8 option").eq(0).prop("selected", true);
//do the same for the rest, change the ID
});

Categories

Resources