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

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
});

Related

how do i show selected value in option using jquery

i am trying to show a value from database to show in select option
running in PHP,JSON,AJAX,JQUERY
$(document).on('click', '.edit_data', function () {
var shop_id = $(this).attr("id");
$.ajax({
url: "<?php echo base_url();?>dashboard/update_shop",
method: "POST",
data: {shop_id: shop_id},
dataType: "json",
success: function (data) {
$('#emp_name').value = data[0].emp_id;
console.log(data[0].emp_id);
$('#shop_name').val(data[0].shop_name);
$('#shop_owner').val(data[0].shop_owner);
$('#shop_phone').val(data[0].shop_phone);
$('#shop_dist').val(data[0].shop_district);
$('#shop_loc').val(data[0].shop_location);
$('#shop_code').val(data[0].shop_code);
$('#shop_id').val(data[0].shop_id);
$('#latitude').val(data[0].latitude);
$('#longitude').val(data[0].longitude);
$('#create_button').text("Update");
$('#createOrder').modal('show');
}
});
});
i expect the out put comes like show data[0].emp_id as selected and show other option in dropdown
As your question is
how do i show selected value in option using jquery
and I can't comment as my reputation is below 50.
your answer should be $('#idOfSelectTag').val('3')
$(document).ready(function(){
$('#txtValue').change(function(){
changeValue($(this).val());
});
});
function changeValue(){
var value = $('#txtValue').val();
value = value==''? 1: value;
$('#selTest').val(value);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="selTest">
<option value="1">one</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
<br />
<input type="text" id="txtValue" />
<br />
<button onclick="changeValue(4)">Change Value</button>
you can also using php without jquery.
<select class="custom-select col-12" id="lcount" name="lcount" data-validation="required" >
<option value="0" <?php if($sdata['lcount']=='0') echo 'selected="selected"'; ?>>select</option>
<option value="1" <?php if($sdata['lcount']=='1') echo 'selected="selected"'; ?>>1</option>
<option value="2" <?php if($sdata['lcount']=='2') echo 'selected="selected"'; ?>>2</option>
<option value="3" <?php if($sdata['lcount']=='3') echo 'selected="selected"'; ?>>3</option>
<option value="4" <?php if($sdata['lcount']=='4') echo 'selected="selected"'; ?>>4</option>
<option value="5" <?php if($sdata['lcount']=='5') echo 'selected="selected"'; ?>>5</option>
</select>

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 } ?>

passing a html select value to a JS object

So I have a regular HTML form with some inputs and 1 select value that i am passing to a JS object..
I don't know how to grab the value of the selected option.
var dataObj = {
firstName: $("input[name='firstName']", _form).val(),
lastName: $("input[name='lastName']", _form).val(),
lastName2: $("input[name='lastName2']", _form).val(),
email: $("input[name='email']", _form).val(),
oldPassword: $("input[name='oldPassword']", _form).val(),
newPassword: $("input[name='newPassword']", _form).val(),
userType: $("select[name=usertype]", _form).val(),};
I am grabbing al the values of the inputs fine, but the value of the select menu comes undefine... any help for a noob?
<select class="uk-select" name="usertype" id="userType">
<option value="0" <?php if ($UserEdit ->userType == 0) {echo "selected";} ?> >Needs Auth</option>
<option value="1" <?php if ($UserEdit ->userType == 1) {echo "selected";} ?> >Super Admin</option>
<option value="2" <?php if ($UserEdit ->userType == 2) {echo "selected";} ?> >Supervisor</option>
<option value="3" <?php if ($UserEdit ->userType == 3) {echo "selected";} ?> >Operator</option>
<option value="4" <?php if ($UserEdit ->userType == 4) {echo "selected";} ?> >Hotel Admin</option>
<option value="5" <?php if ($UserEdit ->userType == 5) {echo "selected";} ?> >Guest</option>
<option value="6" <?php if ($UserEdit ->userType == 6) {echo "selected";} ?> >Visitor</option>
</select>
You're almost there. You wanna use the :selected psuedo selector:
userType: $("select[name='usertype'] option:selected").val()
// or it could be .text()
userType: $("select[name='usertype'] option:selected").text()
//without the attribute select - give it an id
userType: $("#userType option:selected").text()
Learn jQuery has a great page on exactly what you're doing:
Learn jQuery
I put an id# on the select tag and used this userType: $("#userType option:selected", _form).attr('value'), in my javascript to grab the value. It worked like a charm. The main issues is that I was trying to grab the value of select, which technically it doesn't have. So I needed to grab the attribute value of the selected option.

how to select a specific option when a condition exists

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>

How to set selected value of an array - I have this form many times

I have dropdown and it is an array. I'm using JavaScript to clone this dropdown when button "Add" is clicked. So it is appeared many times and it is inserted correct. But when I try to set selected value of this dropdown, when I press submit values of all forms of this dropdown becomes the same. I think this is because I use set_select('labeling[]') as array like this:
<option value=''" . set_select('labeling[]', '') . " role='menuitem'> </option>
But when I try to use it like that:
<option value=''" . set_select('labeling', '') . " role='menuitem'> </option>
it doesn't set selected anything. My view is:
<select name="labeling[]" id="labeling" class="dropdown">
<option value=''" . set_select('labeling[]', '') . " role='menuitem'> </option>
<option value="1" <?php echo set_select('labeling[]', '1'); ?> role="menuitem">1</option>
<option value="2" <?php echo set_select('labeling[]', '2'); ?> role="menuitem">2</option>
<option value="3" <?php echo set_select('labeling[]', '3'); ?> role="menuitem">3</option>
<option value="4" <?php echo set_select('labeling[]', '4'); ?> role="menuitem">4</option>
</select>
How could I do that - to be selected values for each dropdown? :) Thanks!
I edited my question. My whole code is:
$(document).ready(function () {
$('.multi-field-wrapper').each(function () {
var $wrapper = $('.multi-fields', this);
$(".add-field", $(this)).click(function (e) {
var $template = $('.multi-field:first-child', $wrapper).clone(true);
$template.find('input', 'select').val('').focus();
$template.appendTo($wrapper);
});
});
<div class="container multi-field-wrapper">
<div class="multi-fields">
<div class="multi-field">
<div class="row">
<div class="col-md-4 col-md-offset-1 col-sm-3">
<div class="form-group">
<select name="labeling[]" id="labeling" class="dropdown">
<option value=''" . set_select('labeling[]', '') . " role='menuitem'> </option>
<option value="firm1" <?php echo set_select('labeling[]', 'firm1'); ?> role="menuitem">firm1</option>
<option value="firm2" <?php echo set_select('labeling[]', 'firm2'); ?> role="menuitem">firm2</option>
<option value="firm3" <?php echo set_select('labeling[]', 'firm3'); ?> role="menuitem">firm3</option>
<option value="firm4" <?php echo set_select('labeling[]', 'firm4'); ?> role="menuitem">firm4</option>
</select>
</div>
</div>
</div>
</div>
</div>
</div>
First of all lets assume your page name is "A.php". Create a hidden field in this page. ex:
<input type="hidden" id="unique_index" value="0" />
<select name="labeling[]">
<option value="1" <?php echo set_select('labeling[]', '1', TRUE, 0); ?> role="menuitem">1</option>
<option value="2" <?php echo set_select('labeling[]', '2', FALSE, 0); ?> role="menuitem">2</option>
<option value="3" <?php echo set_select('labeling[]', '3', FALSE, 0); ?> role="menuitem">3</option>
</select>
Now, in javascript (where you were cloning the element earlier that is the function which get invoked on click of button), write a get call like this:
var newIndex = $('#unique_index').val();
var cnt = parseInt(newIndex)+1;
$.get( "new_ajax_page_url.php", { counter: cnt} )
.done(function( data ) {
data.find('input', 'select').val('').focus();
data.appendTo($wrapper);
});
Now in the new_ajax_page_url.php, which will only contain:-
$newCounter = $_GET['counter'];
$str = <<<EOD
<select name="labeling[]">
<option value="1" set_select('labeling[]', '1', TRUE, $newCounter) role="menuitem">1</option>
<option value="2" set_select('labeling[]', '2', FALSE, $newCounter) role="menuitem">2</option>
<option value="3" set_select('labeling[]', '3', FALSE, $newCounter); role="menuitem">3</option>
</select>
EOD;
echo $str;
+++++++
Hope it is helpful :like:
Try this If I am understanding you problem correctly:
This is a sample case, try to do the way ci does:-
$options = array(
'small' => 'Small Shirt',
'med' => 'Medium Shirt',
'large' => 'Large Shirt',
'xlarge' => 'Extra Large Shirt',
);
echo form_dropdown('shirts', $options, 'large');
// Would produce:
<select name="shirts">
<option value="small">Small Shirt</option>
<option value="med">Medium Shirt</option>
<option value="large" selected="selected">Large Shirt</option>
<option value="xlarge">Extra Large Shirt</option>
</select>
Do let me know If anything is incorrect anywhere?
You need to set the array indices yourself; example:
labeling[0]
labeling[1]
labeling[2]
Without those indices each option will overwrite the previous one.
Whether or not an option is the current selected item is controlled by the SELECTED attribute in the option.
<select name="labeling[]" id="labeling" class="dropdown">
<option value="1" role="menuitem">1</option>
<option value="2" SELECTED role="menuitem">2</option>
<option value="3" role="menuitem">3</option>
<option value="4" role="menuitem">4</option>
</select>
You haven't shown much of your code so I can only guess based on what you say that when you submit it loses the ability to properly process the PHP function that you are calling. In this case I would recommend either generating the page with the SELECTED option in the appropriate locations or using Javascript to add SELECTED to the appropriate options in your lists.
if you are using set_select() on your first select box the integer passes should be 0, on your second select box it should be 1, and so on.... Now the set_select() function does know which key should be used and is able to set the correct value as selected for all your select boxes with an array as field name, YAY!
HTML will look like this:
<select name="labeling[]">
<option value="1" <?php echo set_select('labeling[]', '1', TRUE, 0); ?> role="menuitem">1</option>
<option value="2" <?php echo set_select('labeling[]', '2', FALSE, 0); ?> role="menuitem">2</option>
<option value="3" <?php echo set_select('labeling[]', '3', FALSE, 0); ?> role="menuitem">3</option>
</select>
<select name="labeling[]">
<option value="1" <?php echo set_select('labeling[]', '1', TRUE, 1); ?> role="menuitem">1</option>
<option value="2" <?php echo set_select('labeling[]', '2', FALSE, 1); ?> role="menuitem">2</option>
<option value="3" <?php echo set_select('labeling[]', '3', FALSE, 1); ?> role="menuitem">3</option>
</select>

Categories

Resources