Add class for children element depend on input value with jQuery - javascript

I have two fieldsets:
<fieldset class="checkable">
<span class="as_cp_checkbox"></span>
<input type="hidden" name="register_condition_01" id="register_condition_01" value="no">
<label for="register_condition_01">data</label>
</fieldset>
<fieldset class="checkable">
<span class="as_cp_checkbox"></span>
<input type="hidden" name="register_condition_02" id="register_condition_02" value="yes">
<label for="register_condition_02">data</label>
</fieldset>
Now: i need to add checked class to span.as_cp_checkbox if in my input value is yes. I try with that but every time this class is appending for first fieldset.
var checkable_fieldset = $('fieldset.checkable'),
checkable_fieldset_input = checkable_fieldset.find('input');
if (checkable_fieldset_input.val('yes')){
checkable_fieldset_input.parent(checkable_fieldset).prev().children('span').addClass('checked');
}
How can i add class for this prev span which input have yes value?

You can do this to add the class checked to all 'span.as_cp_checkbox' preceding an input whose value is "yes" :
$('input').filter(function(){return $(this).val()=="yes";})
.prev('span.as_cp_checkbox')
.addClass('checked');
Demonstration

checkable_fieldset_input.val('yes') sets the value to yes.
you need to do checkable_fieldset_input.val() == 'yes'

Your condition in the if statement should read
checkable_fieldset_input.val() == 'yes'
Right now you are assigning the value yes.

$('fieldset.checkable input').each(function(_, input){
if($(input).val() == 'yes')
{
$(input).siblings('span.as_cp_checkbox').addClass('checked');
}
});

Related

How to remove a part of the content of a div with jQuery?

When I click on a checkbox, I append some content to a div (#item_list)
if(cb_new.prop('checked')) {
$("#item_list").append("<input type='hidden' name='post[]' value="+ this.value +">");
} else {
// ??
}
When I uncheck the box I want that exact same string to be removed from the div. Keeping all the others that have a different value (this.value).
So for example I could have:
<div id="item_list">
<input type="hidden" name="post[]" value="102">
<input type="hidden" name="post[]" value="93">
</div>
But if I uncheck
<input type="checkbox" id="d-102-2" name="d-102" value="102" data-id="d-102">
I want :
<div id="item_list">
<input type="hidden" name="post[]" value="93">
</div>
If I check it again, I want it back.
How can I do that?
A vanilla JS solution would look like:
Updated according to your expanded requirements.
document.querySelector(`#item_list input[value='${this.value}']`).remove();
This will query the DOM, find an input element, with a value attribute whose value is equal to this.value, and remove it from the DOM with the remove() method.
A more detailed implementation isn't easy to give without having more information.
You can use the data attribute to assign unique id to the checkbox, once it is checked, input element with same data-uid is added and once unchecked we remove the input element with same data-uid
$(document).ready(function() {
$("#cb_new").change(function() {
if ($(this).prop('checked')) {
$("#item_list").append($("<input data-uid='"+$(this).data('uid')+"' type='text' name='post[]' class='newItem' value='" + $(this).val() + "'>"));
} else {
$('.newItem[data-uid='+$(this).data('uid')+']').remove();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="checkbox" id="cb_new" data-uid="8080" value="tick Me" name="test"/><label for="test">Tick Me</label>
<div id="item_list" style="border:1px solid tomato">
</div>

How I can get the value of the input type radio using jQuery the value contains spaces

I used this code I also used AJAX in my page
$html.='<div><p id="question" name="qid">Q.'.$result['question_no'].': '.$result['question'].'</p></div>
<label style="padding-top:15px;">
A <span style="padding-left: 15px;"><input type="radio"';
if (isset($result['answer']) && $result['answer']==$result['choice1']) {
$html.= 'checked="checked"';
}
$html.=' name="answer" id="option" value='.$result['choice1'].'>'.$result['choice1'].'</span>
</label>
</div>
And the jQuery part is
var answer = $("form input[type='radio']:checked").val();
alert(answer);
The value contain spaces like 'primary key' but I got only primary how can I get value with spaces
The solution is really simple you just forgot to put double quotes for the value attribute, value attribute must be wrapped in double quotes here is the corrected code,
$html.='<div><p id="question" name="qid">Q.'.$result['question_no'].': '.$result['question'].'</p></div>
<label style="padding-top:15px;">
A <span style="padding-left: 15px;"><input type="radio"';
if (isset($result['answer']) && $result['answer']==$result['choice1']) {
$html.= 'checked="checked"';
}
$html.=' name="answer" id="option" value="'.$result['choice1'].'">'.$result['choice1'].'</span>
</label>
</div>';
Now the jquery will pick the value correctly
Why don't you ensure that the value comes in snake_case like primary_key, then process it to what you want after getting it with JQuery.
Something like:
var answer = $("form input[type='radio']:checked").val();
alert(answer.split("_"));
hi here is a working solution for your problem. feel free to modify the code to make it fit for your needs
<!-- including jquery library -->
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
/* When input of type button is clicked then call this function */
$("input[type='button']").click(function(){
/* load value of input with name gender in a JS variable radioValue */
var radioValue = $("input[name='gender']:checked").val();
/* check if there is some value in radioValue variable... if there is no value then if block will not execute */
if(radioValue){
alert(radioValue);
}
});
});
</script>
<input type="radio" name="gender" value="Gender male">Male
<input type="radio" name="gender" value="Gender female">Female
<input type="button" value="Get Value"></p>

How to get multiple selected from input value?

I am trying to show multiple selected option of a person from selected value.
Here is an example but not working.
I want to do like this dynamically .
Basicly you need a trigger("chosen:updated")
I'd updated your fiddle, you can find here http://jsfiddle.net/ebilgin/hdz8f1b6/2/. I hope it works for you.
Add this to css (for example):
.result-selected{color:white !important; background:blue !important;}
$('.value').val('demo 1,demo 2');
$('.chosen-select').val($('.value').val().split(',')) // set value, accepts array
$('.chosen-select').chosen();
$('.chosen-select').on('change', function() {
values = $('.chosen-select').val();
$('.value').val(values);
}) ;
HTML
1. General Events.
<input type="checkbox" name="GE[]" value="Brainometer>
<input type="checkbox" name="GE[]" value="Hot Seat">
<input type="checkbox" name="GE[]" value="Mind Drill>
<input type="checkbox" name="GE[]" value="Techno Art>
<input type="checkbox" name="GE[]" value="Photography">
If U Want to get multiple selected option of a person from selected value Using PHP: use implode... multiple value can be store in $ge depends on what the user select...
PHP
if(isset($_POST['GE'])){
$ge = implode(", ",$_POST['GE']);
}else{
$ge = "";
}</p>

jQuery Check if Checkbox is Checked, then Add Value to Input Field

I have a shopping cart checkout page and I'm trying to add a "gift" option. What needs to happen: Once the checkbox is selected for "Send Order As Gift", a value needs to be assigned to a hidden input field so that the information is moved onto the confirmation page and various receipts.
HTML:
<h3>Send Order As Gift</h3>
<ul>
<li class="fc_row fc_gift"><label for="gift" class="fc_pre">This is a gift,
please do not include a receipt.</label>
<input type="checkbox" name="gift" id="gift" class="checkbox" value="" />
<input type="hidden" name="Gift" id="gift-true" value="" /></li>
<script type="text/javascript">
$(document).ready(function(){
$("#gift-true").input( $('#edit-checkbox-id').is(':checked').val() + "Yes");
});​
</script>
</li>
<li class="fc_row fc_gift_message"><label for="Gift Message">Include a message
(limit 100 characters):</label>
<textarea name="Gift Message" cols="50" rows="3" maxlength="100"></textarea>
</li>
</ul>
You have to update your hidden field whenever the checkbox is changed:
$(function(){
$('#gift').change(function() {
$("#gift-true").val(($(this).is(':checked')) ? "yes" : "no");
});
});
Use jQuery .val() to set the value of the input element. jquery .is() returns a boolean value, so you will have to check if it is true (using an if statement or a ternary operator like below), then conditionally update the value. Also, you should update this value whenever the box is selected/unselected:
$(document).ready(function(){
$('#edit-checkbox-id').change(function() {
$("#gift-true").val( this.checked ? "Yes" : "" );
}
});​
Also, if your checkbox is:
<input type="checkbox" name="gift" id="gift" class="checkbox" value="" />
The appropriate id-selector is $('#gift'), not $('#edit-checkbox-id')
$('#edit-checkbox-id').is(':checked') returns a boolean value true/false based on checkbox state. So you should use it as a condition and decide what to set the the value using val jQuery method. Try this.
$("#gift-true").val( $('#edit-checkbox-id').is(':checked') ? "Yes": "No" );
you can use CSS Pseudo-classe for example :
var checked=$('input[id="#gift-true"]:checked').length;
var isTrue=false;
if(checked)
isTrue=true;
else
isTrue=false;

How to clear radio button in Javascript?

I have a radio button named "Choose" with the options yes and no. If I select any one of the options and click the button labeled "clear", I need to clear the selected option, using javascript. How can I accomplish that?
You don't need to have unique id for the elements, you can access them by their name attribute:
If you're using name="Choose", then:
With recent jQuery
$('input[name=Choose]').prop('checked',false);
With old jQuery (<1.6)
$('input[name=Choose]').attr('checked',false);
or in pure JavaScript
var ele = document.getElementsByName("Choose");
for(var i=0;i<ele.length;i++)
ele[i].checked = false;
Demo for JavaScript
If you do not intend to use jQuery, you can use simple javascript like this
document.querySelector('input[name="Choose"]:checked').checked = false;
Only benefit with this is you don't have to use loops for two radio buttons
This should work. Make sure each button has a unique ID. (Replace Choose_Yes and Choose_No with the IDs of your two radio buttons)
document.getElementById("Choose_Yes").checked = false;
document.getElementById("Choose_No").checked = false;
An example of how the radio buttons should be named:
<input type="radio" name="Choose" id="Choose_Yes" value="1" /> Yes
<input type="radio" name="Choose" id="Choose_No" value="2" /> No
An ES6 approach to clearing a group of radio buttons:
Array.from( document.querySelectorAll('input[name="group-name"]:checked'), input => input.checked = false );
Wouldn't a better alternative be to just add a third button ("neither") that will give the same result as none selected?
In my case this got the job done:
const chbx = document.getElementsByName("input_name");
for(let i=0; i < chbx.length; i++) {
chbx[i].checked = false;
}
Simple, no jQuery required:
clear
<script type="text/javascript">
function clearChecks(radioName) {
var radio = document.form1[radioName]
for(x=0;x<radio.length;x++) {
document.form1[radioName][x].checked = false
}
}
</script>
YES<input type="radio" name="group1" id="sal" value="YES" >
NO<input type="radio" name="group1" id="sal1" value="NO" >
<input type="button" onclick="document.getElementById('sal').checked=false;document.getElementById('sal1').checked=false">
if the id of the radio buttons are 'male' and 'female', value reset can be done by using jquery
$('input[id=male]').attr('checked',false);
$('input[id=female]').attr('checked',false);
Somtimes i have to remove attribute checked from inputs type="radio" :
let el = document.getElementById('your_input_id');
el.checked = false;
el.removeAttribute('checked');
<form>
<input type="radio" name="btn"> Item1
<input type="radio" name="btn"> Item2<br>
<input type="reset">
</form>
This could work..

Categories

Resources