How can I reset my many chosen-select boxes values? - javascript

I have a problem with using a chosen-select plugin.
I have many select boxes and I made it using javascript code.
I want to reset all my select box when I change my "default-chosen" class, but in my screen the showing text is a default message ("select an option ...") not a my message "not chosen".
This is not real code, but similar.
function appendSelectBox(i) {
$(myTable).append(
"<select id=\select-a" + i + "\" class=\"form-control chosen-select for-history select-a\">" +
"<option value=\"-1\">not chosen</option>" +
"</select>");
}
for (var i = 0; i < 10; i++) {
appendSelectBox(i);
}
$(".select-term").chosen().change(function(event) {
var trIndex = tableForm.getTrIndex($(this));
tableForm.addTermUrl(trIndex);
});
$(".default-chosen").chosen().change(function(event) {
// here is the code that remove selected option and set default value
})
I tried all codes like bottom codes.
$('.select-a').find('option:first-child').prop('selected', true).end().trigger('chosen:updated');
$('.select-a').find('option').removeAttr('selected').end().trigger('chosen:updated');
$('.select-a').val(-1).trigger("chosen:update");
$('.select-a').val(-1).trigger("liszt:update");
$('.select-a').val("-1").trigger("chosen:update");
$('.select-a').val("").trigger("chosen:update");
please help,, :[

In my case, my chosen change event listener was reset, so I have to re-register in my code..

Related

How can I perform dynamic operations on dynamically added elements?

My objective:
Filling in the 'performer-payments' table dynamically with JS/Jquery
For each (dynamically added) row in the table, one of the data cells contains a dropdown box.
This dropdown box should, when a certain option is selected, make visible another dropdown box (in the same cell). Otherwise, this second dropdown should be invisible.
Elsewhere I am accomplishing the hide/show dynamics by means of a toggleVisible function, which simply adds custom classes which is marked by css to hide or show the element.
The relevant code:
The table I want to populate:
<table id='performer-payments' class='performer-profile payments-table'>
<tr>
<th> Period </th>
<th> Amount </th>
<th> Paid? </th>
</tr>
</table>
The code that populates the table:
for (period in data['Performers'][performer]['Payments']) {
var amount = utils.calcPerformerCut(data, performer, period);
var row = "<tr>";
row += "<td> " + period + " </td>";
row += "<td> " + amount + " $ </td>";
row += "<td>";
row += "<div class='performer-profile payment-status'>";
row += data['Performers'][performer]['Payments'][period];
row += "</div>";
row += "<select id='payment-status-" + performer + "-" + period + "' class='perfomer-profile hidden-onload displayNone payment-status-menu'>";
row += "<option value='paid'>Paid</option>";
row += "<option value='unpaid'>Unpaid</option>";
row += "<option value='transfer'>Transfer to...</option>";
row += "</select>";
row += "<select id='payment-transfer-period-" + performer + "-" + period + "' class='performer-profile hidden-onload displayNone payment-period-menu'>";
for (var i=0; i < data['Periods'].length; i++) {
row += "<option value='" + period + "'>" + period + '</option>';
}
row += "</select>";
row += "</td>";
row += "</tr>";
$('#performer-payments').append(row);
$('#performer-payments').on('change', {perf: performer, per: period}, function (even) {
if (even.target.value == 'transfer') {
utils.toggleVisible($('#payment-transfer-period-' + even.data.perf + '-' + even.data.per), true);
} else {
utils.toggleVisible($('#payment-transfer-period-' + even.data.perf + '-' + even.data.per), false);
}
});
}
For reference, the code that toggles visibility:
exports.toggleVisible = function (selector, visible) {
if (visible) {
selector.removeClass('displayNone').addClass('displayBlock');
} else {
selector.removeClass('displayBlock').addClass('displayNone');
}
}
There are (at least) two issues with this:
The #payment-transfer-period-... select box is never displayed, even when the 'transfer' option is chosen in the first select box. From debugging efforts it seems to me that it could be that the #payment-transfer-period-.. for some reason is not a valid object yet, or something like that.
(Obviously, really), the on-change event is triggered N times (N=number of periods) because I am just telling the program to trigger whenever something in the table changes. I would like it to trigger only for the relevant dropdown, but when I tried adding the #payment-status-... as a selector to the .on() function, it made it never trigger.
Note: I welcome feedback on this in general - I am an experienced programmer but have very little experience with HTML/JS/Jquery. Further, I have decided to not use templates for this project since I am trying to learn the basics, so if you get pancreatitis from seeing the way I am 'dynamically' adding the rows to the table, I apologize but it is partly intentional.
Other than that, please ask for clarifications if something is not clear here.
Edit: Here is the relevant part of the data structure:
data = {
'Performers': {
'Dira Klaggen': {
'Payments': {
'Q1': 'Paid',
'Q2': 'Paid',
'Q3': 'Unpaid'
},
},
'Holden Bolden': {
'Payments': {
'Q2': 'Transferred to Q3',
'Q3': 'Unpaid'
}
},
'Manny Joe': {
'Payments': {
'Q1': 'Paid',
'Q2': 'Unpaid',
'Q3': 'Unpaid',
}
}
},
'Periods': [
'Q1',
'Q2',
'Q3'
]
}
You do not attach the change handler to the right element. I should be the first select in the row... Instead of the whole table.
Try this change handler:
$('#performer-payments').find('#payment-status-' + performer + '-' + period).on('change', function(){
if ($(this).val() == 'transfer') {
$(this).next('select').show();
} else {
$(this).next('select').hide();
}
});
Second approach:
You could simplify that by using a class instead of a "complicated" unique id for the first select.
Say you use the class "payment-status":
The handler would be:
$('#performer-payments').on('change', '.payment-status', function(){
if ($(this).val() == 'transfer') {
$(this).next('select').show();
} else {
$(this).next('select').hide();
}
});
And this handler can be out of the row appending loop because it uses delegation.
Let's clean up your code by doing the following things:
Use classes instead of ugly IDs.
Use data-attributes or hidden input fields to hold extra information.
Use event delegation to bind dynamically-created elements. Inside the event handler, use tree traversal methods to limit the scope of the search based on the current element this.
Let's apply these things.
Build each row like this. {PLACEHOLDER} is where you put your variable stuff like you have in your code.
<tr>
<td>{PERIOD}</td>
<td>{AMOUNT} $ </td>
<td>
<div class='performer-profile payment-status'>
{SOMETHING-RELATING-TO-PERFORMER-PAYMENT-PERIOD}
</div>
<!-- remove ID -->
<!-- store performer and period in data-attributes -->
<select class='perfomer-profile hidden-onload displayNone payment-status-menu' data-performer='{PERFORMER}' data-period='{PERIOD}'>
<option value='paid'>Paid</option>
<option value='unpaid'>Unpaid</option>
<option value='transfer'>Transfer to...</option>
</select>
<!-- remove ID -->
<select class='performer-profile hidden-onload displayNone payment-period-menu'>
<option value='{PERIOD}'>{PERIOD}</option>
<option value='{PERIOD}'>{PERIOD}</option>
<option value='{PERIOD}'>{PERIOD}</option>
<!-- etc -->
</select>
</td>
</tr>
In your JavaScript, create a delegated event handler. Note the syntax.
$(function () {
// ...
for (period in data['Performers'][performer]['Payments']) {
// build and append row
}
// create delegated event handler once and outside FOR loop
$(document).on('change', '.payment-status-menu', function () {
// get the current status menu
var statusMenu = $(this);
// find its related period menu
var periodMenu = statusMenu.closest('tr').find('.payment-period-menu');
// toggle its visibility
periodMenu.toggle(this.value == 'Transfer');
// of course, this could be a one-liner
//$(this).closest('tr').find('.payment-period-menu').toggle(this.value == 'Transfer');
});
});
It doesn't seem like you need (2.) but if you do, within the event handler, use statusMenu.data('performer') or statusMenu.data('period') to get its performer and period values. You could also do this.dataset.performer or this.dataset.period.

Get selected radio button value from "for loop"

I need a help from you all. In my website, I am generating different colour shades from a selected color. Till here it works fine but after generating different shades, when I select a radio button associated with shades, I get value of first shade no matter how many random radio buttons I select
And the color hex value is coming from array... I want to get the value of selected radio button and store it into html5 localstorage. localstorage works fine if i enter simple text instead of selected radio button value. Please have a look
I am positing my code below:
function makeTableRowColors(colors, displayType)
{
var tableRow = "<tr>";
for (i = 0; i < colors.length; i++)
{
if (displayType == "colors")
{
tableRow += "<td style=\"background-color:" + "#" + colors[i].toString(16) + ";width:85px;height:75px;border-radius:5px;\";><input type='radio' class='ShadeRadioButtons' name='rsSelections' style='position:relative;top:-24px;' value='#"+colors[i].toString(16).toUpperCase()+"'></td>";
}
else
{
tableRow += "<td class=\"rgb-value\">#" + colors[i].toString(16).toUpperCase() + "</td>";
}
}
tableRow += "</tr>";
return tableRow;
}
You didn't post your HTML or the localStorage code you are attempting, but the code should make sure to get the value property, as in:
radButton.value
This code works for me: https://jsfiddle.net/10factxr/1/

Creating two drop down list that are dependent on the first

I am creating three drop down lists with all the possible options in my html. However, I need for them to change as the previous options are picked (hide and display the right ones). I got the second one to tie in to the first, I can't tie the third one in. How do I do this with this same style of code?
http://jsfiddle.net/cL2tt/115/
$(document).ready(function() {
var optarray = $("#optthree").children('option').map(function() {
return {
"value": this.value,
"option": "<option value='" + this.value + "'>" + this.text + "</option>"
}
})
$("#opttwo").change(function() {
$("#optthree").children('option').remove();
var addoptarr = [];
for (i = 0; i < optarray.length; i++) {
if (optarray[i].value.indexOf($(this).val()) > -1) {
addoptarr.push(optarray[i].option);
}
}
$("#optthree").html(addoptarr.join(''))
}).change();
})
See my answer to a similar question, showing 2 different ways.
Changing the values in a <select> using another <select> using AJAX (PHP)

Select menu behaving strangely with AJAX

I have a dropdown whose options get filled dynamically:
function populateDropdown(dropdownNum) {
// invokeWebService uses $.ajax
json = invokeWebService("GET", "/webservice/dropwdownOptions");
optionsHtml = "";
$.each(json, function(count, jsObj) {
optionValue = jsObj.name
optionsHtml+="<option>" + optionValue + "</option>";
});
var dropdownId = "#NRdropdown_" + dropdownNum;
$(dropdownId).html(optionsHtml);
}
function display(blockNum) {
var url = "/webservice/blocks" + blockNum;
var response = invokeWebService("GET", url);
var replacementHtml = "";
var currBlock = "blah";
$.each(response, function(i, block) {
currName = block.name;
var textfield = "<input type='text' id='blockValue" + block.id +
"'>";
var dropdownMenu = "<select id=\"NRdropdown_" + i +
"\"onClick=\"populateDropDown(" + i +
")\"><option>Existing Blocks</option>"
var submitButton = "<input type='submit' value='UPDATE' id='" +
block.id + "'><br><br>";
replacementHtml = currName + textfield + dropdownMenu + submitButton;
});
$("#main").html(replacementHtml);
}
The javascript function "populateDropdown(dropdownNum)":
Makes the ajax request
Parses the json response for the option values into an html string called optionsHtml
Replaces the inner html of the select element with the option values via:
var dropdownSelector = "#NRdropdown_" + dropdownNum;
$(dropdownSelector).html(optionsHtml)
1) When I click on the dropdown arrow, I STILL see "Existing Blocks".
2) After 1 sec I see the first dynamically generated option UNDERNEATH the "Existing Blocks" option, I don't see the other dynamically generated options.
3) Then I click outside the dropdown and see the dropdwon showing the first dynamically generated value.
4) Finally I click the dropdown arrow again and it works as it should with all the dynamically generated values.
How do I make it work so that:
When the page first loads, the dropdown shows "Existing Blocks".
Once I click the dropdown arrow, the dropdown should show all dynamically generated values without the "Existing Blocks" value.
Thanks!
the dropdown listener should be for onmousedown, not onclick

Lose focus of select-option when rebuilding option list

I am dynamically setting the options of my select-fields. Every time the form changes, new data is received from a Servlet and the current selections are overwritten.
Problem here is, that if I select an option, the form loads the javascript function, and I loose my selection / focus.
var capacityOptionsAsString = "";
for(var i = 0; i < capacityArray.length; i++) {
capacityOptionsAsString += "<option value='" + capacityArray[i] + "'>" + capacityArray[i] + "</option>";
console.log('capacity option: ' + capacityOptionsAsString);
}
$("select[name='inptCapacity']").find('option').remove().end().append($(capacityOptionsAsString));
Any idea how to keep the selection?
Edit: Maybe I was not clear enough. I want to keep the selection. So it has to be validated, if the option is selected, if it is, we have to select it again.
Just set the focus again:
$("select[name='inptCapacity']").focus();
Update
get selected option:
var selected_value = $("select[name='inptCapacity'] option:selected").val()
Do your changes
$("select[name='inptCapacity']").find('option').remove().end().append($(capacityOptionsAsString));
Select it again:
$('select[name='inptCapacity'] option[value="' + selected_value + "]').attr('selected', 'selected');
You totally need an id for your select ;)
$('select[name="inptCapacity"]').is(':focus');
$('form[name="formName"] :input').change(function() {
// keep the select focus always on input change
$('select[name="inptCapacity"]').focus();
});

Categories

Resources