I am attempting to build a Selectmenu for my Jquery Mobile 1.3.1 app. I want to trigger a change event to update totals based on the items selected from the Selectmenu.
First I build the list of options that I re-use:
var options = "<option value='NR'>Not Reached</option> ";
options += "<option value='ALT'>Alternate</option> ";
Then I build a callback that will update the totals
var selects = new Array();
//callback to update the totals on change
var changeCallback = function(event, ui) {
var totals = new Object();
selects.forEach(function(select) {
value = select.value;
total = totals.value;
if(total) {
++total;
totals.value = total;
}
else {
totals.value = 1;
}
})
_updateTotals(totals);
};
Then I loop through to build the select boxes. Here's where I build the select box and add the callback:
var select = "<select name=" + selectName + " id=" + selectName + "> ";
select += options;
select += "</select>";
select.on( "change", changeCallback);
select = jQuery.parseHTML(select)[0];
selects.push(select);
Problem is that when the bind gets executed, it jumps from the loop to the return, which I'm assuming indicates an error.
Related
Believe me, I've been looking for examples online for hours. None of them seem to help.
I'm working on making a table. There are some columns with dropdown menu and I've assigned ID to each menu. Inside a loop, I'm trying to assign selected value for each dropdown menu.
var row$ = $('<tr/>');
function updateDataBodyGenerator(myList) {
for (var i = 0 ; i < myList.length ; i++) {
var row$ = $('<tr/>');
var colIndex = 0;
for (var key in myList[i]) {
var cellValue = myList[i][columns[colIndex]];
if (cellValue == null) { cellValue = ""; }
var severityDropDownMenu = "severityDropDownMenu" + i;
colIndex++;
switch (key) {
case "Test Case":
...
break;
case "Test Result":
...
break;
case "Severity":
var severitySting = '<td><select id="' + severityDropDownMenu + '" class="dropDownMenu">' +
'<option value="Red">Red</option>' +
'<option value="Green">Green</option>'+
'<option value="Yellow">Yellow</option>';
row$.append($(severitySting));
//failed
//$("#severityDropDownMenu" + i).val(cellValue);
//failed
//var selectorString = "#" + severityDropDownMenu.toString();
//$(selectorString).val("Green");
//failed
//$("#" + severityDropDownMenu).val(cellValue);
//failed
//var selectorString = '#' + severityDropDownMenu;
//$(selectorString).val(cellValue);
//works
//$('#severityDropDownMenu0').val(cellValue);
...
As you can see in the comments, I've tried several approaches and only 1 worked which was $('#severityDropDownMenu0').val(cellValue); but that will only change 1 dropdown menu.
I appreciate your time and assistance.
Currently you're trying to use the # selector to target the dropdown by ID.
The issue here (as mentioned in the comments) is that this selector will search the DOM for the element, however because you've never added this element to the DOM, it doesn't exist on the page; the selector will return nothing.
What you can do instead is actually turn your severitySting into a jQuery element to set its value. Whenever you do append it, the value will be properly set. Like so:
var $severity = $(severitySting); //This is the <td>
var $dropdown = $severity.find("select") //This is the <select>
$dropdown.val(cellValue); //Set dropdown value
Demo:
var severityDropDownMenu = "mytest";
var cellValue = "Yellow";
var severitySting = '<td><select id="' + severityDropDownMenu + '" class="dropDownMenu">' +
'<option value="Red">Red</option>' +
'<option value="Green">Green</option>' +
'<option value="Yellow">Yellow</option>';
var $severity = $(severitySting);
var $dropdown = $severity.find("select");
$dropdown.val(cellValue);
$("tr").append($severity);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr></tr>
</table>
take your time to read my explanation and ask me if i didn't explain myself well, thanks.
Don't mind how i print whith php, it it okay this way, this is a php setting.
i have in a template an input number that the client will fill with an amount of pallets, in the same template i have a table with as many tr as boxes the order has.
so, there are as many selects as tr, because it is used to assign the box to a pallet.
When the process is done i have the info in my database and if the client enters again he will need to have all the data in place, so the input number is filled and that fills all the selects with the amount of otions as the input, ok.
the fill process is made with jquery.
in the template, i have only this to make the select
<td><select class="pallets_assign" name="boxes[<?=$box;?>][which_pallet]"></select></td>
UPDATE:
to load the options in the selects i use this inside a document ready :
var someone = function() {
var something = function(from_pallets, to_pallets) {
var qty = $(from_pallets);
var select = $(to_pallets);
var update = function() {
select.empty();
for (var i = 1; i <= qty.val(); i++) {
select.append('<option value="' + i + '">' + i + '</option>');
}
};
qty.on('change', update);
update();
}
});
form the tamplate i call it like this:
var init = function() {
someone.something('#total_pallets', '.pallets_assign');
};
total_pallets is the id of the input number
My question is: how do i mark as selected the option which value i have stored in my database if i don't have the options created when the DOM is loaded but when that input number changed?
Thanks for your time.
Thanks to #AlonEitan to helping me find a way to solve this
in the template i had a script that did something like this:
var init = function() {
someone.something('#total_pallets', '.pallets_assign');
};
changed to:
var init = function() {
var option = [];
<? foreach ($products as $product) { ?>
<? for ($i = 1; $i <= count($product["boxes"]); $i++) { ?>
option.push(<?=(somechecks ? $product["boxes"][$i]["which_pallet"] : false);?>);
<? } ?>
<? } ?>
someone.something('#total_pallets', '.pallets_assign', option);
};
and in my js file i had this:
var someone = function() {
var something = function(from_pallets, to_pallets) {
var qty = $(from_pallets);
var select = $(to_pallets);
var update = function() {
select.empty();
for (var i = 1; i <= qty.val(); i++) {
select.append('<option value="' + i + '">' + i + '</option>');
}
};
qty.on('change', update);
update();
}
});
which is now:
var someone = function() {
var something = function(from_pallets, to_pallets, option) {
var qty = $(from_pallets);
var select = $(to_pallets);
var update = function() {
select.empty();
select.each(function(i) {
for (var j = 1; j <= qty.val(); j++) {
$(this).append('<option value="' + j + '"' + (j == option[i] ? ' selected="selected"' : '') + '>' + j + '</option>');
}
});
};
qty.on('change', update);
update();
}
});
It is a shame that in the beginning this got that many downvotes because i think is a cool way to solve this kind of issue and people will profit of this, but anyway.
I currently have a drop down menu that lists all the years from 1970 to present. At the moment this is in some embedded JavaScript within the HTML. I'm trying to use an external file to perform the same function with jQuery, but I'm having difficulty.
This is the current method to display the drop down menu:
<h4 class="form_title">Time Span</h4></br>
<label for="select" class="col-lg-2 control-label">From:</label>
<div class="col-lg-3">
<select class="form-control" name="timeStart" id="select">
<option value="" selected disabled>Select</option>
<script type="text/javascript">
// get current year and then use loop to populate options
var year = new Date().getFullYear();
for(i = year; i >= 1970; i--) {
document.write('<option value="' + i + '">' + i + '</option>');
};
</script>
</select>
</div> <!-- col-lg-3 -->
This works fine but I want to separate the logic from the view. I have tried removing the script entirely from this file and then adding the following in my JavaScript file like so:
var year = new Date().getFullYear();
$("#select").change(function() {
console.log("Calling function successfully...");
for(i = year; i >= 1970; i--) {
document.write('<option value="' + i + '">' + i + '</option>');
}
});
I put the console.log in there to see if the function is even being called when I select the menu (which it isn't). I have been trying many variations on this but can't figure out what I'm doing wrong (probably several things). Should I be selecting the select tag or the option tag?
Move your code into ready and use append to add option to the select.
var year = new Date().getFullYear();
$(document).ready(function () {
console.log("Calling function successfully...");
var options = '';
for (i = year; i >= 1970; i--) {
options += '<option value="' + i + '">' + i + '</option>';
}
$('#select').append(options);
});
You need to append the options you want to render as children to the select element:
$(document).ready(function() {
console.log("Calling function successfully...");
var options = ''
for(i = year; i >= 1970; i--) {
options += '<option value="' + i + '">' + i + '</option>';
}
$("#select").append(options);
});
Since you're using JQuery, you'll need to make sure to wrap your code in $(document).ready(function() {});
If you don't, it'll just try and run immediately on load. Wrapping it in that will ensure that the select box is rendered before trying to run your code.
You can see an example of how this works here.
http://jsbin.com/rebahiwupi/1/edit
$(document).ready(function() {
var sel = $('select');
var start_year = 1970;
for(var i=start_year;i<=new Date().getFullYear();i++) {
sel.append('<option value="'+i+'">'+i+'</option>');
}
});
Another version that uses while loop.
var year = new Date().getFullYear(), $options = $();
while (year >= 1970) {
var option = year--;
$options = $options.add($('<option/>', { 'value': option, 'text': option }));
}
$('#select').append($options);
I have created a depending on radio button click listbox will display now if user click a one radio button listbox will display and again user select other option but its not clear a previous value of listbox how to clear it by javascript????
<script language="JavaScript" type="text/javascript">
function fun(s)
{
if(s==B)
{
document.getElementById("maingroup").style.display='none';
document.getElementById("subgroup").style.display='';
document.getElementById("itemname").style.display='none';
}
if(s==C)
{
document.getElementById("maingroup").style.display='none';
document.getElementById("subgroup").style.display='none';
document.getElementById("itemname").style.display='';
}
</script>
Here is the example which i have tried JS FIDDLE
Try this:
var listBox = document.getElementById("listboxID");
listBox.innerHTML = "";
I think show/hide method is not good for programming.
I dont know whether it is useful or not but this might be helpful to you.
You can make it dynamic like
var mainGroup = ["aa","bb","cc"];
var subGourp = ["dd","ee","ff"];
var itemName = ["gg","ee","ff"];
var Country = ["jj","hh","ii"];
var Zone = ["kk","ll","mm"];
if(s == A)
{
var i=0;
var str = "";
for(i=0;i<mainGroup.length;i++)
{
str += "<option value='" + (i+1) + "'>" + mainGroup[i] + "</option>";
}
document.getElementById("maingroup").style.display='';
document.getElementById("maingroup").innerHTML = str;
}
else if(s == B)
{
var i=0;
var str = "";
for(i=0;i<subGourp.length;i++)
{
str += "<option value='" + (i+1) + "'>" + subGourp[i] + "</option>";
}
document.getElementById("maingroup").style.display='';
document.getElementById("maingroup").innerHTML = str;
}
This is my idea(not tested). Give every your listbox a class name like class='lst'. After that when you click on a radio button just use:
`document.getElementsByClassName('lst').style.display = 'none';`
and show current listbox.
`document.getElementsByClassName('currentListboxID').style.display = 'block';`
Here is DEMO
I use to populate Dropdown using javascript:
function populateDDL(ddl_id) {
var option_str = "";
var x;
for(x in datalist){
option_str += " <asp:ListItem Value='" + datalist[x] + "' Text='" + datalist[x] + "'></asp:ListItem>"
}
var country_div = document.getElementById(ddl_id);
country_div.innerHTML = option_str;
}
This is sure the datalist is not empty and also Dropdown list populated perfectly..but dnt know why after clicking on my page add button I am not getting the selected value.
Thanks
You should use client side select list control rather than server control to whome you are trying to fill at client side. Its surprised ...
But you should use select control
function populateDDL(ddl_id) {
var option_str = "<select id='ddl_id'>";
var x;
for(x in datalist){
option_str += " <option value='" + datalist[x] + "'>" + datalist[x] + "</option>";
}
option_str += "</select>";
var country_div = document.getElementById(ddl_id);
country_div.innerHTML = option_str;
}