When selecting all radio buttons with knockout, it doesnt recognize the input - javascript

This fiddle clarifies things And my selectAll method with pure jquery.
self.selectAll = function( data, event){
$(".dataQueryRadioBtn").each(function() {
$( this ).prop('checked', true );
});
}
When you click on one of the radio buttons and then on Click Me a message shows you the number of the clicked radio button. When you do the same now first clicking on Select All it doesn't show every radio button. Only those you clicked yourself. Why is that so?

The problem is that Knockout has no way to know that the checked property of your <input> has been changed because you only registered a click handler for each.
You can solve this easily by triggering the click event:
$(".dataQueryRadioBtn").prop('checked', false).click();
But generally, when you're in the realms of your viewModel (just like in your selectAll method) you shouldn't rely on DOM elements (it's the elements that should rely on your view-model, not the opposite) to fetch data but rather explicitly change the observable value.
And in your case:
function ViewModel () {
var self = this;
// ...
self.allPossibleTags = []
self.selectAll = function(data, event){
self.selectedTags(self.allPossibleTags);
}
}
// upon document.ready
$(document).ready(function() {
var viewModel = new ViewModel();
viewModel.allPossibleTags = $('.dataQueryRadioBtn').get().map(function(elm) { return elm.value });
ko.applyBindings(viewModel);
});
See Fiddle

Related

How to check which element caused an on change event to fire

Js novice here. I've got a few unfinished pages I've inherited, on one page there are two drop downs which use an on change jquery event to create child dropdowns once a value is selected in the first one.
After speaking with the user it is not desired for one of these drop downs to do that. The two sets of drop downs have different names and IDs but the same classes. I'd like to catch the name or ID of which drop down was modified in the event but so far have had no luck syntactically doing that.
EDIT: I've added the on change event code here for reference. The html dropdowns are generated by some really wonky nested partial views
$(document).on("change",
".genericClass",
function () {
$(this).addClass("updated");
if ($(this).hasClass("blank")) {
$(this).removeClass("blank");
var $newAddRow = $(this).parents(".relationControl:first").find(".relationAddRowTemplate")
.clone().removeClass("relationAddRowTemplate")
.addClass("relationAddRow")
.show();
$newAddRow.insertAfter($(this));
}
});
you can use below code, you will the get the id of select element caused event triggered
$(document).on("change",
".genericClass",
function () {
alert($(this).attr('id'));
$(this).addClass("updated");
if ($(this).hasClass("blank")) {
$(this).removeClass("blank");
var $newAddRow = $(this).parents(".relationControl:first").find(".relationAddRowTemplate")
.clone().removeClass("relationAddRowTemplate")
.addClass("relationAddRow")
.show();
$newAddRow.insertAfter($(this));
}
});
you have two options:
1- Use listener
select.addEventListener( 'change', event => {}); then event.target
2- add scope watch
$scope.$watch(function () { return self.selectedValue; }, function (newValue, oldValue) {
if (newFilter != oldFilter) {
// call what ever you want
}
}, true);

How to go through array with dynamically added elements with jquery?

I have a HTML table created with javascript where i have possibility to add new rows (dynamically added elements). In one of the tds i have an input field that fires a bootstrap modal to open. In the modal I have radiobuttons with options and when OK button is clicked the value from the radiobutton is set in the inputfield. The problem is that the value gets updated on every row, not just the row i clicked.
Since the elements are added dynamically i used
$(document).on('click', 'input', function (e) {
doSomething();
});
Any idea how to solve this problem?
Updated with more code
$(document).on('click', 'input', function (e) {
var inputForm = e.target;
modal.modal({show:true});
modal.find(".btn-success").click(function () {
var choice = $("modal").find('input[type=radio]:checked').val();
if (choice) {
modal.modal('hide');
inputForm.value = choice;
}
});
});
Without any furter information about the code you are running it's hard to help you.
But, you might be able to use the target property of the event (e), to look at what element actually triggered the click, to be able to see which row/textbox to update when the modal is closed.

How to refresh drop down when click on select using jquery?

I have a drop down in mvc
#Html.DropDownList(
"Name",
new SelectList(Model.Product, "Value", "Text"),
string.Concat("-- ", "Please select the item", " --"),
new { id = "Product", Class = "form-control" }
)
I fill dropdown dynamically. It works fine. Everything works fine. When i change the item i perform action that i want using jquery onchange method and refresh the dropdown. But i want to refresh dropdown when user click on "Please select the item". When i click on please select the onchange method is not called. How i can do this?
$DropDown.on("change", function () {
//Here i perfome action
});
You might want to extract the "onchange" function in order to reuse it. Something like that
var changeCallback = function(e) {
// chage logic
}
$("#dropdownlistname").on("change", changeCallback);
$("#dropdownlistname").on("click", changeCallback);
$(document).ready(function(){
$('#dropdownlistname').change(function(e){
// Your event handler
});
// And now fire change event when the DOM is ready
$('#dropdownlistname').trigger('change');
});
More Information Here
Edit
You should provide a selector to the on function:
$(document).on('change', 'input', function() {
// Does some stuff
});
In that case, it will work as you expected. Here is the Fiddle using on function
user2052156's answer looks good but if you want the 'click' to happen only the first time then you can remove the click handler after the first call:-
$DropDown.on('click change', function(){
//Here i perfome action
$(this).off('click');
});
Fiddle

$(this) is alerting previous selected values in jquery

I am using $(this) to get the current selected(clicked) element of a specific class .For the first time its coming fine i.e i am getting the selected element but as soon as i click on second time it is giving the alert of the old as well as new selection .I am not able to find out what is the issue..
Here is the code..
$('.l-one').click(function () {
var tableName = $(this).text();
//Table Name Lable
$("#lbl").text(tableName);
//Panel
$("#Perticulars").show();
$('.my-new-three').click(function () {
var dishvalue = $(this).text(); //get the value of dish item and display in the table
//console.log(dishvalue);
alert(tableName);
alert(dishvalue);
if (localStorage.getItem(tableName) != null) {
alert("b");
In the alert(tableName); i am getting alert of all the tables selected previously .Please help me to resolve this..
Thanks...
use below code . only click assign events to each time when you click '.l-one'. so if you click '.l-one' 3 time 'click' event assign 3 time to '.my-new-three'.
unbind() function remove event from element and bind() function attach event to element. so here as per your code each time when you click '.l-one' unbind remove click event from '.my-new-three' and bind function again assign click event to '.my-new-three'.
$('.my-new-three').unbind('click').bind('click',function () {});
other way is to use separate click event methods.
$('.l-one').on('click', function () { });
$('.my-new-three').on('click',function () {})
Use separate click handler instead of using click handler insider another one. Consider this code:
$('.l-one').click(function () {
//code
}
$('.my-new-three').on("click",function () {
//code
}
Assuming If .my-new-three exists inside .l-one or .my-new-three creating dynamically then use this:
$('.l-one').on("click",".my-new-three",function () {
//code
}

Prototype, listening to a change in radio buttons

I've been searching for a solution for days for this, so I hope you can help.
I'm using custom form elements by Ryan Fait, which lets you style checkboxes, and radio buttons etc.
The only problem is I can't use onClick events anymore, since the actual box gets overwritten with a with the images for the custom radio elements.
The javascript does actually change the radio buttons, but I can't seem to find a way to detect changes..
Currently, I've tried this:
Event.observe(window, 'load', function() {
$('startquestion').observe('change', set_startanswer(this.value));
});
HTML:
<p>
<input type="radio" class="styled" name="startanswer" id="startquestion" value="'.$startq['id'].'" onclick="if (this.checked == true) { set_startanswer(this.value); }"'.$s.'> <span id="startanswertext'.$startq['id'].'">'.$startq['question'].'</span>
</p>
Though, it doesn't seem to be working.
Can anyone help me?
Cheers!
Danny
Easiest way to observe the change event on Radio list :
Form.getInputs('form','radio','radio_name').find(function(radio){
Event.observe(radio, 'change', function() {
//do whatever on this change
});
});
The script you are using hides the original checkboxes and displays some custom graphics above. It registers the clicks on the graphics and sets the hidden checkbox accordingly - but programmatically setting the checkbox states won't fire change events.
To work around this issue you can probably explicitly catch clicks on the custom graphics (the script creates a wrapping p element). Using your code lines from above:
Event.observe(window, 'load', function() {
var startquestionElement = $('startquestion');
var startquestionState = startquestionElement.checked;
startquestionElement.up().observe('click', function() {
if (startquestionElement.checked != startquestionState) {
startquestionState = startquestionElement.checked;
set_startanswer(startquestionElement.value); // are you sure you want to use the element's value and not it's checked state?
}
});
});
Another alternative would be to globally observe the checkbox state by using a timer and checking e.g. every 100 ms:
Event.observe(window, 'load', function() {
var startquestionElement = $('startquestion');
var startquestionState = startquestionElement.checked;
var observingInterval = setInterval(function() {
if (startquestionElement.checked != startquestionState) {
// If you want to stop observing after the checkbox has changed it's state once,
// uncomment the following line:
// clearInterval(observingInterval);
startquestionState = startquestionElement.checked;
set_startanswer(startquestionElement.value); // are you sure you want to use the element's value and not it's checked state?
}
}, 100);
});
You could use the latter version to check for multiple checkboxes in one observing function call.
You can include event.simulate.js from protolicious and then fire a native click event on the image element directly.
$('id_of_button').simulate('click');

Categories

Resources