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;
Related
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>
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>
When page loads, there are 10 checkboxes. When I click on Select all check box all 10 check boxes gets selected. Now I add 10 more records dynamically (using ajax) having checkboxes (Total 20 check boxes on page). Now I click on Select All check box, Original checkboxes i.e. first 10 check boxes gets unchecked (newly added 10 are as it is i.e. unchecked). Again I click on Select All check box, at this time all 20 check boxes should get selected but nothing is getting selected.
$(".productListed").attr( "checked", true ); and $(".productListed").attr( "checked", false );
$(document).on('click', "#selectall", function(){ // my code });
I have gone through Event binding on dynamically created elements?
How to set all dynamically added checkbox to checked/unchecked when I click on Select All?
I don't think this is the case of event binding of dynamically created elements.
I have created a working example - see http://jsfiddle.net/qwt7s0a7/
HTML
<div class="container">
<input class="cb" type="checkbox"/>
</div>
<button id='add'>Add checkbox</button>
<button id='selectAll'>Select all</button>
js
$(function(){
$('#add').click(function(){
$('.container').append('<input class="cb" type="checkbox"/>');
});
$('#selectAll').click(function(){
var checked = $('.container .cb').first().prop('checked');
$('.container .cb').prop('checked', !checked)
});
});
Please find the sample code below and example at: https://jsfiddle.net/vv48fh3t/
Html
<input type="button" id="btnCheckAll" value="Check All"/>
<input type="button" id="btnAddNew" value="Add checkbox" >
<div class="checkDiv">
<input type="checkbox" class="chk"/>check 1
<input type="checkbox" class="chk"/>check 2
<input type="checkbox" class="chk"/>check 3
<input type="checkbox" class="chk"/>check 4
</div>
JS
$(document).ready(function(){
$("#btnCheckAll").click(function(){
$(".chk").each(function(){
$(this).prop("checked","checked");
});
});
$("#btnAddNew").click(function(){
for(var i=0;i<5;i++){
$(".checkDiv").append("<input type='checkbox' class='chk'/>check "+i);
}
});
});
I Used .prop("checked", true) instead of attr( "checked", true )
$(".productListed").prop( "checked", true ); and $(".productListed").prop( "checked", false );
Also use this whenever you want to read any dynamically added element on HTML document page.
$(document).on('click', "#selectall", function(){ // my code });
I have a form which contains radio boxes.
<input type="radio" name="categoryid" id="category420" value="420" onclick="checkCategory();" > Category1
<input type="radio" name="categoryid" id="category1314" value="13,14" onclick="checkCategory();" >Category2
<input type="radio" name="categoryid" id="category594" value="594" onclick="checkCategory();" >Category3
When the radio elements value attribute is a comma separated list (13,14) I need the elements Id attribute to change.
In the example above, when the second category is selected then "CategoryIDs=13,14" should be passed to the action page not categoryid. But for the other two categories it should pass categoryid value.
I cannot edit the action page.
The question: How can I change the radio buttons Id attribute in JQuery?
Change the Id
Based on your requirement to have only one Id (categoryid/s) then you could change the Id using JQuery, before the form is submitted.
JSFiddle working example - http://jsfiddle.net/daTYY/
JQuery
$(function() {
$('input:radio[name=categoryid]').change(function() {
if ($(this).val().indexOf(",") >= 0) {
$(this).attr("id","newId");
}
});
});
Update a hidden input
Add a hidden input named categoryids. Then use JQuery to check if categoryid contains a comma and if it does populate categoryids with the value.
JSFiddle working example - http://jsfiddle.net/KVs79/
HTML
<input type="radio" name="categoryid" id="categoryid1" value="13,14" />Category2
<input type="radio" name="categoryid" id="categoryid2" value="404" />Category3
<input type="hidden" name="categoryids" id="categoryids" value="" />
JQuery
$(function() {
$('input:radio[name=categoryid]').change(function() {
if ($(this).val().indexOf(",") >= 0) {
$("#categoryids").val("13,14");
}else{
$("#categoryids").val("");
}
});
});
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');
}
});