Using dynamically filled combobox's new value in another function - javascript

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

Related

Show specific value in dropdown

I have a table where in each row for each id we have 'Client' column. When a user clicks on the row he is able to change client. I am using jquery.dialog for this operation. When a dialog appears the user sees a dropdownlist with Clients. How I can make that after dialog appears, the user sees the current client as the selected item in the dropdown? I've tried as below:
onDblClickRow: function (row, $element) {
$.getJSON('/ManageProjects/GetAvaibleClients/', function (clients) {
if (clients.length == 0) {
$('#clientNameEdit').empty();
$('#clientNameEdit').append('<option value="0">Tasks</option>');
}
$.each(clients, function (index, clientt) {
$('#clientNameEdit').append("<option value='" + clientt.Value + "'>" + clientt.Text + "</option>");
});
})
var currentClient = row.clientName; // Client name from Row
$('#clientNameEdit select').val(currentClient); // Tried to set like that
}
but doesn't work
The value passed in to .val needs to be the clientt.Value and not the text name.
if you dont have the clientt.Value, then try something like:-
$("#clientNameEdit option[text=" + currentClient + "]").attr("selected", true);
And bring the setting of the select inside of the success function.
The following alteration to your code snippet should do the trick:
onDblClickRow: function (row, $element) {
$.getJSON('/ManageProjects/GetAvaibleClients/', function (clients) {
if (clients.length == 0) {
$('#clientNameEdit').empty();
$('#clientNameEdit').append('<option value="0">Tasks</option>');
}
$.each(clients, function (index, clientt) {
$('#clientNameEdit').append("<option value='" + clientt.Value + "'>" + clientt.Text + "</option>");
});
var currentClient = row.clientName; // Client name from Row
$('#clientNameEdit').val(currentClient); // Tried to set like that but doesn't work
});
As indicated above, if you do the currentClient = row.clientName outside the success of the ajax call, it will probably fire before the dropdown is populated and therefore not have any effect.
Secondly the jQuery selector '#clientNameEdit select' should only be '#clientNameEdit' as it refer to the dropdown itself and not it's parent.

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) {

JQuery set select box value to selected

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

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

Different behavior with .val() and .attr("value") using ajax return data on a clone()'d but uninserted element

As the title says, I'm trying to set the value of a .clone()'d form field using the results of a $.getJSON() request. All of the return values have the same key as the name attribute of the form field they belong to.
Naturally, I tried to use .val("foo") to deal with cross-browser/field type discrepancies but it wouldn't work. Oddly, .attr("value","foo") does.
Any ideas? Is this expected behavior, or an undocumented quirk? Here is the relevant code snippet:
function showSites(){
$.getJSON("process.php?action=showSites", function(data) {
var items = [];
$.each(data.sites, function(key, val) {
var $form = $("#addSiteForm").clone();
var buttons = '<button id="getCert" class="button" href="getCert.php?id=' + val.id + '">Get Cert</button>'
+ '<button id="updateSite" class="button" href="process.php?action=updateSite&id=' + val.id + '">Update Site</button>'
+ '<button id="deleteSite" class="button" href="process.php?action=deleteSite&id=' + val.id + '">Delete Site</button>';
// set siteId
$form.find("input[name=siteId]").attr("value",val.id);
// change values
$.each(val, function(i,v){
$form.find("[name="+i+"]").val(v);
});
items.push('<h3>' + val.name + '</h3>');
items.push("<div class='site'>");
items.push("<form class='siteForm' id='"+val.id+"'>");
items.push($form.html());
items.push("</form>");
items.push(buttons);
items.push("</div>");
});
var foo = items.join('');
$("#sites").prepend(foo).accordion("destroy").accordion();
});
});
You can use .val() property in input tags( text box, textarea,..) only.
attr("attrname","value") this is used to set value to any tags. You can set some dummy attr in div tag and retrieve value attr("attrname");

Categories

Resources