JQuery set select box value to selected - javascript

Please help i am doing this to use in my mobile with jquery mobile
var obj = jQuery.parseJSON(finalresult);
//alert(obj);
var dept = '2';
$(document).ready(function () {
//$("#opsContactId").empty();
$.each(obj, function (k, v) {
var $opt = $("<option/>");
$opt.attr("value", k);
//alert(k);
//alert(v);
//var value1=v;
if (k == dept) {
//$opt.attr("selected","selected");
//alert("in if");
$("#opsContactId").val(k);
//document.getElementById("opsContactId").value=k;
// $('#opsContactId').selectmenu('refresh', true);
}
$opt.text(v);
$opt.appendTo($("#opsContactId"));
});
});
not able to set an option to be selected by dafault

As others as stated, jQuery's .prop() would be the most suitable answer here as jQuery Docs mention themselves:
"The .prop() method should be used to set disabled and checked instead of the .attr() method. The .val() method should be used for getting and setting value."
To further your on your example, jQuery allows for method 'chaining' which returns the jQuery object after the method has completed, thus you can add another method directly after it.
<select id="opsContactId">
</select>
<script>
$(document).ready(function() {
var tmp = [ 1, 2, 3, 4, 5 ],
dept = 2;
$.each( tmp, function( k, v ) {
$("<option/>").attr("value", k)
.text( "Value - " + v)
.appendTo( $("#opsContactId") )
.prop( 'selected', ( k == dept ? 'selected' : '' ));
});
});
</script>
Fiddle: http://jsfiddle.net/twdgC/
Later I forgot you mentioned the jQuery mobile aspect of your question, which changes the dynamic of the question a little bit. The snippet above is run after the page has loaded (Thus, all the jQuery mobile attachments have already been set/made), which would happen to give you the result of (below)
Fiddle: http://jsfiddle.net/5ksG8/
This obviously isn't helpful when trying to construct an <select> list, thus we'll need to append the snippet above with:
$("#opsContactId").selectmenu('refresh', true );
After the snippet has run, thus it 'reloads' the entire list, finally providing you with (below)
Fiddle: http://jsfiddle.net/YxVg6/
You were doing this in your original snippet, the issue was - you were executing it within the loop (And it was commented out!).

Would something like this not be easier?
Would something like this not be easier?
var selected = "selected"; // work this out
var text = "Option Text"; // work this out
var value = "Option Value"; // work this out
$("#opsContactId").append('<option value="' + value + '" '+ selected + '>' + text + '</option>');

jsBin demo
if you have a match you'll need to add the attribute selected. however I don't know how your object looks like...
var obj = {"1":"one","2":"two","3":"three","4":"four"}; // let's say that's how it looks
var dept = '2';
$(function () {
var $sel = $("#opsContactId");
$.each(obj, function (k, v) {
var $opt = $("<option/>", {value:k, text:v}).appendTo( $sel );
if (k == dept) $opt.prop({selected:true});
});
});

Related

Using dynamically filled combobox's new value in another function

I fill combobox dynamically with javascript;
var $select = $('#itemsize');
$select.empty();
$(data).each(function (index, o) {
$select.append('<option value="' + o.Size + '">' + o.Size + '</option>');});
That code is running perfectly and running another function after that (GetProductInfoWhereSize).
I'm using this combobox's selected value in that function.
Function like this;
function GetProductInfoWhereSize() {
var size = -$("#itemsize").val();
console.log(size);
}
But GetProductInfoWhereSize shows me old values.
How do I use new value in this function?
Sorry for bad English.
Thanks.
Maybe you are using the function in the onchange event of the select, try with this:
$( "#itemsize option:selected").val();

Getting a 'Cannot find variable' error trying to access a json object

hopefully somebody can help me. The JS below, loads a JSON file and parses the counties into a select menu. It also removes duplicates. Now in the JSON feed, each item has something like this:
{
"County":"Antrim",
"Town":"Antrim Town",
"Restaurant":"Diane's Restaurant & Pizzeria"
}
What I am trying to do is in the first select menu, once the user chooses the county, the second select menu is updated with values from the son object. At the moment I'm getting a 'Cannot find variable' error and I can't work out why. Is the data array not available for some reason?
<script type="text/JavaScript">
$(document).ready(function(){
//get a reference to the select elements
var county = $('#county');
var town = $('#town');
var restaurant = $('#restaurant');
//request the JSON data and parse into the select element
$.getJSON('rai.json', function(data){
console.log(data);
//clear the current content of the select
$('#county').html('');
$('#county').append('<option>Please select county</option>');
$('#county').html('');
$('#town').append('<option>Please select town</option>');
$('#restaurant').html('');
$('#restaurant').append('<option>Please select restaurant</option>');
//iterate over the data and append a select option
$.each(data.irishtowns, function(key, val) {
county.append('<option id="' + val.County + '">' + val.County+ '</option>');
});
var a = new Array();
$('#county').children("option").each(function(x){
test = false;
b = a[x] = $(this).text();
for (i=0;i<a.length-1;i++){
if (b ==a[i]) test =true;
}
if (test) $(this).remove();
});
});
$( "#county" ).change(function() {
var myCounty = $(this).val();
console.log(myCounty);
$.each(data.irishtowns, function(key, val) {
if (val.Town === myCounty) {
town.append('<option id="' + val.Town + '">' + val.Town + '</option>');
}
});
});
});
</script>
Data is not in scope in this line
$.each(data.irishtowns, function(key, val) {
You could move this up into the callback, or use a global variable to provide access: i.e. in the callback have a line countries = data and then
$.each(countries.irishtowns, function(key, val) {

How I find the checkbox by id and apply attribute on string using JQuery?

I have a following html string of contentString:
var content =
'<div id="content">' +
'<div>' +
'<input name="tBox" id="select" type="checkbox" value="" '+
'onclick="changeView()"> Select for operation' +
'<p style="text-align:right">View details</p>' +
'</div>' +
'</div>';
Here, How I find the checkbox select by id and add attribute checked on changeView() function?
function changeView(m) {
//find the select id from content string
var checkbox = content.find($('#select'+m));
// Apply the checked property on checkbox.
checkbox.attr("checked","checked");
}
Thanks in advance.
If you convert it to a JQuery object first then you can do it like this:
var contentObj = $(content);
var checkbox = contentObj.find("#select");
checkbox.attr("checked", true);
then if you need it back at html string:
content = contentObj[0].outerHTML;
Note: If outerHTML is not working as expected, the following JQuery can be used as an alternative:
content = contentObj.clone().wrap('<div>').parent().html();
If m is meant to be the id you want to find (e.g. "select"), then use this:
var checkbox = contentObj.find("#" + m);
Live Example: Here is a working example
Here is the complete function for easy reference:
function changeView(m) {
var contentObj = $(content);
var checkbox = contentObj.find("#" + m);
checkbox.attr("checked", true);
content = contentObj[0].outerHTML;
}
You need to compile the string into a DOM object first by wrapping it in a jQuery call first. Then you can use the find method.
So:
var dom = $(content),
select = dom.find('#select');
In any case, there is no need to add the 'checked' attribute, because when you click the checkbox, it will automatically become checked.
If however, you want to still programmatically check it:
select.on('click', function () {
this.attr('checked', 'checked');
});
Simply like this
function changeView(m) {
//find the select id from content string
var checkbox = content.find('#select');
// Apply the checked property on checkbox.
checkbox.attr("checked","checked");
}
if you want to pass id then
function changeView(m) {
//find the select id from content string
var checkbox = content.find("#" + m);
// Apply the checked property on checkbox.
checkbox.attr("checked","checked");
}
Since you're using the onclick handler, you don't really need to do any of that :
in html : onclick="changeView(this);"
function changeView(box) {
if(box.checked) { stuff; }
// or get jquery ref to that box :
$(box).prop("checked", true);
}

$(this).attr("id") not working

as the title says, I keep getting "undefined" when I try to get the id attribute of an element, basically what I want to do is replace an element with an input box when the value is "other".
Here is the code:
function showHideOther(obj) {
var sel = obj.options[obj.selectedIndex].value;
var ID = $(this).attr("id");
alert(ID);
if (sel == 'other') {
$(this).html("<input type='text' name='" + ID + "' id='" + ID + "' />");
} else {
$(this).css({
'display': 'none'
});
}
}
The HTML:
<span class='left'><label for='race'>Race: </label></span>
<span class='right'><select name='race' id='race' onchange='showHideOther(this);'>
<option>Select one</option>
<option>one</option>
<option>two</option>
<option>three</option>
<option value="other">Other</option>
</select>
</span>
It is probably something small that I am not noticing, what am I doing wrong?
Change
var ID = $(this).attr("id");
to
var ID = $(obj).attr("id");
Also you can change it to use jQuery event handler:
$('#race').change(function() {
var select = $(this);
var id = select.attr('id');
if(select.val() == 'other') {
select.replaceWith("<input type='text' name='" + id + "' id='" + id + "' />");
} else {
select.hide();
}
});
your using this in a function, when you should be using the parameter.
You only use $(this) in callbacks... from selections like
$('a').click(function() {
alert($(this).href);
})
In closing, the proper way (using your code example) would be to do this
obj.attr('id');
Because of the way the function is called (i.e. as a simple call to a function variable), this is the global object (for which window is an alias in browsers). Use the obj parameter instead.
Also, creating a jQuery object and the using its attr() method for obtaining an element ID is inefficient and unnecessary. Just use the element's id property, which works in all browsers.
function showHideOther(obj){
var sel = obj.options[obj.selectedIndex].value;
var ID = obj.id;
if (sel == 'other') {
$(obj).html("<input type='text' name='" + ID + "' id='" + ID + "' />");
} else {
$(obj).css({'display' : 'none'});
}
}
You could also write your entire function as a jQuery extension, so you could do something along the lines of `$('#element').showHideOther();
(function($) {
$.extend($.fn, {
showHideOther: function() {
$.each(this, function() {
var Id = $(this).attr('id');
alert(Id);
...
return this;
});
}
});
})(jQuery);
Not that it answers your question... Just food for thought.
What are you expecting $(this) to refer to?
Do you mean sel.attr("id"); perhaps?
Remove the inline event handler and do it completly unobtrusive, like
​$('​​​​#race').bind('change', function(){
var $this = $(this),
id = $this[0].id;
if(/^other$/.test($(this).val())){
$this.replaceWith($('<input/>', {
type: 'text',
name: id,
id: id
}));
}
});​​​
I had a similar issue.
`var ID = $(this).attr("id");`
sometimes using this method with arrow function (`
$('div).click(()=>{
console.log($(this).attr("id"))
}
`)
)Could result in undefined output so instead better using the keyword 'function'
In the function context "this" its not referring to the select element, but to the page itself
Change var ID = $(this).attr("id");
to var ID = $(obj).attr("id");
If obj is already a jQuery Object, just remove the $() around it.
I recommend you to read more about the this keyword.
You cannot expect "this" to select the "select" tag in this case.
What you want to do in this case is use obj.id to get the id of select tag.
You can do
onchange='showHideOther.call(this);'
instead of
onchange='showHideOther(this);'
But then you also need to replace obj with this in the function.

Adding options to a <select> using jQuery?

What's the easiest way to add an option to a dropdown using jQuery?
Will this work?
$("#mySelect").append('<option value=1>My option</option>');
Personally, I prefer this syntax for appending options:
$('#mySelect').append($('<option>', {
value: 1,
text: 'My option'
}));
If you're adding options from a collection of items, you can do the following:
$.each(items, function (i, item) {
$('#mySelect').append($('<option>', {
value: item.value,
text : item.text
}));
});
This did NOT work in IE8 (yet did in FF):
$("#selectList").append(new Option("option text", "value"));
This DID work:
var o = new Option("option text", "value");
/// jquerify the DOM object 'o' so we can use the html method
$(o).html("option text");
$("#selectList").append(o);
You can add option using following syntax, Also you can visit to way handle option in jQuery for more details.
$('#select').append($('<option>', {value:1, text:'One'}));
$('#select').append('<option value="1">One</option>');
var option = new Option(text, value); $('#select').append($(option));
If the option name or value is dynamic, you won't want to have to worry about escaping special characters in it; in this you might prefer simple DOM methods:
var s= document.getElementById('mySelect');
s.options[s.options.length]= new Option('My option', '1');
This is very simple:
$('#select_id').append('<option value="five" selected="selected">Five</option>');
or
$('#select_id').append($('<option>', {
value: 1,
text: 'One'
}));
Option 1-
You can try this-
$('#selectID').append($('<option>',
{
value: value_variable,
text : text_variable
}));
Like this-
for (i = 0; i < 10; i++)
{
$('#mySelect').append($('<option>',
{
value: i,
text : "Option "+i
}));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id='mySelect'></select>
Option 2-
Or try this-
$('#selectID').append( '<option value="'+value_variable+'">'+text_variable+'</option>' );
Like this-
for (i = 0; i < 10; i++)
{
$('#mySelect').append( '<option value="'+i+'">'+'Option '+i+'</option>' );
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id='mySelect'></select>
That works well.
If adding more than one option element, I'd recommend performing the append once as opposed to performing an append on each element.
for whatever reason doing $("#myselect").append(new Option("text", "text")); isn't working for me in IE7+
I had to use $("#myselect").html("<option value='text'>text</option>");
To help performance you should try to only alter the DOM once, even more so if you are adding many options.
var html = '';
for (var i = 0, len = data.length; i < len; ++i) {
html.join('<option value="' + data[i]['value'] + '">' + data[i]['label'] + '</option>');
}
$('#select').append(html);
Why not simply?
$('<option/>')
.val(optionVal)
.text('some option')
.appendTo('#mySelect')
Test here:
for (let i=0; i<10; i++) {
$('<option/>').val(i).text('option ' + i).appendTo('#mySelect')
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="mySelect"></select>
$('#mySelect').empty().append('<option value=1>My option</option>').selectmenu('refresh');
I like to use non jquery approach:
mySelect.add(new Option('My option', 1));
var select = $('#myselect');
var newOptions = {
'red' : 'Red',
'blue' : 'Blue',
'green' : 'Green',
'yellow' : 'Yellow'
};
$('option', select).remove();
$.each(newOptions, function(text, key) {
var option = new Option(key, text);
select.append($(option));
});
You can add options dynamically into dropdown as shown in below example. Here in this example I have taken array data and binded those array value to dropdown as shown in output screenshot
Output:
var resultData=["Mumbai","Delhi","Chennai","Goa"]
$(document).ready(function(){
var myselect = $('<select>');
$.each(resultData, function(index, key) {
myselect.append( $('<option></option>').val(key).html(key) );
});
$('#selectCity').append(myselect.html());
});
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js">
</script>
<select id="selectCity">
</select>
Not mentioned in any answer but useful is the case where you want that option to be also selected, you can add:
var o = new Option("option text", "value");
o.selected=true;
$("#mySelect").append(o);
If you want to insert the new option at a specific index in the select:
$("#my_select option").eq(2).before($('<option>', {
value: 'New Item',
text: 'New Item'
}));
This will insert the "New Item" as the 3rd item in the select.
There are two ways. You can use either of these two.
First:
$('#waterTransportationFrom').append('<option value="select" selected="selected">Select From Dropdown List</option>');
Second:
$.each(dataCollecton, function(val, text) {
options.append($('<option></option>').val(text.route).html(text.route));
});
You can append and set the Value attribute with text:
$("#id").append($('<option></option>').attr("value", '').text(''));
$("#id").append($('<option></option>').attr("value", '4').text('Financial Institutions'));
How about this
var numbers = [1, 2, 3, 4, 5];
var option = '';
for (var i=0;i<numbers.length;i++){
option += '<option value="'+ numbers[i] + '">' + numbers[i] + '</option>';
}
$('#items').append(option);
if u have optgroup inside select, u got error in DOM.
I think a best way:
$("#select option:last").after($('<option value="1">my option</option>'));
We found some problem when you append option and use jquery validate.
You must click one item in select multiple list.
You will add this code to handle:
$("#phonelist").append("<option value='"+ 'yournewvalue' +"' >"+ 'yournewvalue' +"</option>");
$("#phonelist option:selected").removeAttr("selected"); // add to remove lase selected
$('#phonelist option[value=' + 'yournewvalue' + ']').attr('selected', true); //add new selected
$(function () {
var option = $("<option></option>");
option.text("Display text");
option.val("1");
$("#Select1").append(option);
});
If you getting data from some object, then just forward that object to function...
$(function (product) {
var option = $("<option></option>");
option.text(product.Name);
option.val(product.Id);
$("#Select1").append(option);
});
Name and Id are names of object properties...so you can call them whatever you like...And ofcourse if you have Array...you want to build custom function with for loop...and then just call that function in document ready...Cheers
Based on dule's answer for appending a collection of items, a one-liner for...in will also work wonders:
let cities = {'ny':'New York','ld':'London','db':'Dubai','pk':'Beijing','tk':'Tokyo','nd':'New Delhi'};
for(let c in cities){$('#selectCity').append($('<option>',{value: c,text: cities[c]}))}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
<select id="selectCity"></select>
Both object values and indexes are assigned to the options. This solution works even in the old jQuery (v1.4)!
If someone comes here looking for a way to add options with data properties
Using attr
var option = $('<option>', { value: 'the_value', text: 'some text' }).attr('family', model.family);
Using data - version added 1.2.3
var option = $('<option>', { value: 'the_value', text: 'some text' }).data('misc', 'misc-value);
$('#select_id').append($('<option>',{ value: v, text: t }));
This is just a quick points for best performance
always when you are dealing with many options, build a big string and then add it to the 'select' for best performance
f.g.
var $mySelect = $('#mySelect');
var str = '';
$.each(items, function (i, item) {
// IMPORTANT: no selectors inside the loop (for the best performance)
str += "<option value='" + item.value + "'> " + item.text + "</option>";
});
// you built a big string
$mySelect.html(str); // <-- here you add the big string with a lot of options into the selector.
$mySelect.multiSelect('refresh');
Even faster
var str = "";
for(var i; i = 0; i < arr.length; i++){
str += "<option value='" + item[i].value + "'> " + item[i].text + "</option>";
}
$mySelect.html(str);
$mySelect.multiSelect('refresh');
This is the way i did it, with a button to add each select tag.
$(document).on("click","#button",function() {
$('#id_table_AddTransactions').append('<option></option>')
}
You can do this in ES6:
$.each(json, (i, val) => {
$('.js-country-of-birth').append(`<option value="${val.country_code}"> ${val.country} </option>`);
});
Try
mySelect.innerHTML+= '<option value=1>My option</option>';
btn.onclick= _=> mySelect.innerHTML+= `<option selected>${+new Date}</option>`
<button id="btn">Add option</button>
<select id="mySelect"></select>
U can try below code to append to option
<select id="mySelect"></select>
<script>
$("#mySelect").append($("<option></option>").val("1").html("My enter code hereoption"));
</script>

Categories

Resources