Javascript/jQuery: search within object - javascript

I have the following code.
<div class="days">
<input name="days-select" type="radio" value="Mon" > Mon </input>
<br>
<input name="days-select" type="radio" value="Tue" > Tue </input>
</div>
<script>
$(document).ready(function() {
radiobtn = $('.days');
radiobtn.find('value="Tue"').prop('checked', 'checked');
});
</script>
Basically, I need a two-stage search. First, find the group of radio buttons, then set one of them as checked. HOWEVER, I do not want to combine these two steps into one. Thanks for the hint.
BTW, since I am new to Javascript I would like to ask how to debug this code. For example, single-step through the script, and after "radiobtn = $('.days');" check whether "radiobtn" is assigned correctly etc. Thanks again.

HTML
<div class="days">
<input id="dayMonday" name="days-select" type="radio" value="Mon">
<label for="dayMonday">Monday</label>
<br>
<input id="dayTuesday" name="days-select" type="radio" value="Tue">
<label for="dayTuesday">Tuesday</label>
</div>
script
$(document).ready(function () {
//your .days selector is actually getting the div and not the radio button
var div = $('.days');
//maybe here you want to do some things with the div...
//...
var radiobtn = div.find('input[value="Tue"]');
//maybe here you want to do some things with the radio button...
//...
//now you have the correct element...
radiobtn.prop('checked', true);
//F12 in Chrome to see the console
console.log(radiobtn);
//notice the selector property returns: .days input[value="Tue"]
console.log(radiobtn.selector);
//so you could just do this all in one line:
$('.days input[value="Tue"]').prop('checked', true);
//see last commented line regarding this next line...
//$('.days input[value="Tue"]').click(
// function(){ console.log("you clicked Tuesday");});
//Note: you could do this:
//radiobtn.click();
//... or this:
//$('.days input[value="Tue"]').click();
//but it also fires the click event which is why you would see
//"you clicked Tuesday" in the console with the above line uncommented
});
Here's a fiddle.

Related

Display value from only checked checkbox and if other checkboxes are checked uncheck them

Lets say that I have 3 checkboxes:
<input type="checkbox" value="25,99" name="price">
<input type="checkbox" value="15,99" name="price">
<input type="checkbox" value="10,99" name="price">
and I want to display the value of the checked checkbox in a div, but only one checkbox can be active at a time.
I was trying to marry these two examples together but this seams kinda messy and overkill:
only one checked at the time
http://jsfiddle.net/MQM8k/
$('input.example').on('change', function() {
$('input.example').not(this).prop('checked', false);
});
with this link to live
$(document).ready(function() {
$("button").click(function(){
var favorite = [];
$.each($("input[name='sport']:checked"), function(){
favorite.push($(this).val());
});
alert("My favourite sports are: " + favorite.join(", "));
});
});
Thanks
An easy way is to uncheck all the checkboxes as the first thing you do upon detecting a click, and then re-check the one you are on.
$('.prx').click(function(){
$('.prx').prop('checked', false);
$(this).prop('checked', true);
let prx = $(this).val();
$('#msg').text(prx);
});
#msg{margin-top:20px;padding: 10px; background:wheat;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
25.99 <input type="checkbox" class="prx" value="25,99" name="price"><br>
15.99 <input type="checkbox" class="prx" value="15,99" name="price"><br>
10.99 <input type="checkbox" class="prx" value="10,99" name="price"><br>
<div id="msg"></div>
$(document).on("click", ".prx", function (){
var self = $(this);
$('.prx').not(self).prop('checked', false);
self.prop('checked', true);
alert(self.val());
});
You should really consider making this input a radio button.
You're essentially breaking the UX of checkboxes to not allow multiple selections. Radio button inputs do this behavior (one selection at a time) by default, will have expected tab actions for accessibility users and won't need all this extra JS.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/radio

Ignore value radiobuttons - iCheck

I try this way for get a value from radiobuttons (iCheck), but all the time only return the value from the first radio, ignoring the remaining. The theory says that the code is fine, even so it returns badly.
Radio box, get the checked value [iCheck]
My code:
<div class="step row">
<div class="col-md-10">
<h3>YYYYYY.</h3>
<ul class="data-list-2">
<li><input name="p1" id="p1" type="radio" class="required check_radio" value="1"><label>Yes</label></li>
<li><input name="p1" id="p1" type="radio" class="required check_radio" value="0"><label>No</label></li>
<li><input name="p1" id="p1" type="radio" class="required check_radio" value="2"><label>Meybe</label></li>
</ul>
</div>
</div>
<!-- end step -->
My method for get value:
$(document).ready(function() {
$('#p1').on('ifChecked', function(event) { //try ifClicked - ifToggled
alert($(this).val()); // alert value
});
});
All the time return value 1 even when another option is selected.
Please help, I try all the night different ways but doesn't work ;(
I'm not sure how you are generating the ids for your radio buttons, but the id property should always be unique, since you want the same event handling on your radio buttons, just use the class so that it attaches the event to all your radio buttons which belong to that class, then you don't have to add events for each individual id:
So instead of this:
//If you did it this way, you'd have to have one of these blocks for each
//unique id belonging to a radio button
$('#p1').on('ifChecked', function(event){ //try ifClicked - ifToggled
alert($(this).val()); // alert value
});
Change it to this:
//Use the class instead so that the same event handling can be added to all radio
//buttons in one block of code
$('.required.check_radio').on('ifChecked', function(event){ //try ifClicked - ifToggled
alert($(this).val()); // alert value
});

Checkboxes, javascript runs 2 times through function if I click on text

I want to click on a checkbox and if I click this box it should run a function what gets an ID and saves it into an array or deletes it from the array if it still exists in the array.
That works, but if I click on the text beside the box the function runs twice. It first writes the ID into the array and then deletes it.
I hope you can help me so that I can click on the text and it just runs once
HTML
<label><input type="checkbox" value="XXX" >Active</label>
JavaScript/jQuery
function addOrRemoveBoxes(ID){
if(boxArr.indexOf(ID) != -1){
removeFromArray(ID)
}
else{
boxArr.push(ID);
}
}
$(".checkBoxes").unbind().click(function() {
event.stopPropagation();
addOrRemoveBoxes($(this).find('input').val());
});
The problem is probably that your label and your input are picking the click. Try to bind it only to input. Like this:
$(".checkBoxes input").unbind().click(function() {
event.stopPropagation();
addOrRemoveBoxes($(this).find('input').val());
});
Your HTML is structured bad. When your label is clicked it triggers a click event for the input so you have to separate the input form the label like: <input type="checkbox" name="opt1" id="opt1_1" value="ENG"> <label for="opt1_1">hello</label>. Also your jQuery makes no sense, why do you use unbind()? And we can't see what removeFromArray() does (we can guess but I prefer to see all code used or note that you use pseudo code).
I made this in 5 min: (hopes it helps you)
$(document).ready(function(){
window.boxArr = [];
$(document).on('click','[name=opt1]',function(){
addOrRemoveBoxes(this.value);
//show contents of boxArr
if(boxArr.length == 0){
$('#output').html('nothing :/');
}
else{
$('#output').html(boxArr.join(" -> "));
}
});
});
function addOrRemoveBoxes(ID){
var arrayIndex = boxArr.indexOf(ID);
if(arrayIndex > -1){
boxArr.splice(arrayIndex, 1);
}
else{
boxArr.push(ID);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Choose</h1>
<input type="checkbox" name="opt1" id="opt1_1" value="ENG"> <label for="opt1_1">hello</label> <br>
<input type="checkbox" name="opt1" id="opt1_2" value="DUT"> <label for="opt1_2">hallo</label> <br>
<input type="checkbox" name="opt1" id="opt1_3" value="SWE"> <label for="opt1_3">hej</label>
<br><br><h2>Array contains:</h2>
<div id="output">nothing :/</div>
Side note: with [name=opt1] we select all the elements with name="opt1" attribute.

Enabling and disabling all the child elements

I have this issue with enabling and disabling section of fields if other section of fields have specific value.
Consider jsfiddle for html code.
Conditions are
If all the fields of partA are selected as No, then enable partB.
If all the fields of partB are selected as No, then enable partC.
Try 1
First I tried disable elements of PartB and PartC which did not work.
$(function () {
$('.group').attr('name','partB').find('input').attr('disable', true);
$('.group').attr('name','partC').find('input').attr('disable', true);
});
I am not sure how would make sure if all the child elements are selected as No in a group div.
jsBin demo
Having this HTML:
<div class="group" id="partA">
<span> PART A</span><br/>
Option 1
<input type="radio" name="optionsRadios1" value="option1"/>Yes
<input type="radio" name="optionsRadios1" value="option2"/>No
<br />
Option 2
<input type="radio" name="optionsRadios2" value="option1"/>Yes
<input type="radio" name="optionsRadios2" value="option2"/>No
</div>
jQ:
$(function () {
$('#partB, #partC').find('input').prop('disabled', true);
function testChecked(){
var $par = $(this).closest('.group');
var $rad2 = $par.find('[value="option2"]');
var allNo = $rad2.filter(':checked').length == $rad2.length;
$par.next('.group').find(':radio').prop('disabled', !allNo);
if(!allNo){
$par.nextAll('.group').find(':radio').prop({'disabled':true, 'checked':false});
}
}
$('.group :radio').change(testChecked);
});
The above will work also for more than 2 radio groups per .group
Your errors:
"disable", "true" should be "disabled", "true"
<label> can control only one inner element (so I removed it.)
<div> afaik is not supposed to have a name attribute (so I assigned an ID)

Knockout does not recognize manually click

Here is sample http://jsfiddle.net/HhXGH/57/
I am clicking radio button by jquery but knockout.js does not recognize it.Still it shows first clicked value.
<p>Send me spam: <input type="checkbox" data-bind="checked: wantsSpam" /></p>
<div data-bind="visible: wantsSpam">
Preferred flavor of spam:
<div><input type="radio" name="flavorGroup" value="cherry" data-bind="checked: spamFlavor" /> Cherry</div>
<div><input type="radio" name="flavorGroup" value="almond" data-bind="checked: spamFlavor" /> Almond</div>
<div><input type="radio" name="flavorGroup" value="msg" data-bind="checked: spamFlavor" /> Monosodium Glutamate</div>
</div>
var viewModel = {
wantsSpam: ko.observable(true),
spamFlavor: ko.observable('cherry')
};
ko.applyBindings(viewModel);
$(':radio:last').click();
alert(viewModel.spamFlavor())
This because Knockout is subscribing to the click events of checked radio/checkbox elements only. If you checkout the binding handler code for checked. It does this.
var updateHandler = function() {
var valueToWrite;
if (element.type == "checkbox") {
valueToWrite = element.checked;
} else if ((element.type == "radio") && (element.checked)) {
valueToWrite = element.value;
} else {
return; // "checked" binding only
responds to checkboxes and selected radio buttons
}
So in order to get your code to work do this.
$(':radio:last').prop('checked', true).click();
However if the goal is to check the last value, why not just do
viewModel.spamFlavor("msg");
This would achieve the same result.
Hope this helps.
Adding $(':radio:last').attr('checked', true); in addition to triggering click makes it work for me:
http://jsfiddle.net/jearles/HhXGH/61/
I have two different jsFiddles since I'm not sure exactly what your after.
The first jsFiddle will respond via alert when the last radio button is manually clicked.
The second jsFiddle is your posted /57/ jsFiddle without the alert.
Using an alert or console.log with a function will actually invoke that function. That said, after you have manually set the .click() to the last radio button, it's inadvertently reset back to cherry since that's the default value.
RE-EDIT: The second jsFiddle now includes alert written in syntax that doesn't invoke the function & now uses shorted markup.

Categories

Resources