I have a span class "checkbox" and an attribute "value" associated with a hidden input field, both of which are contained within nested divs.
By default the checkbox is unchecked but I would like to change the span class to "checkbox active" and the input value to "1" so that it is checked and rendered to reflect that change.
This code is generated by a Wordpress plugin and there are no ids.
What's the best method to set these two attributes?
<div class="field field-news_item" data-type="true_false" data-name="news_item" data-validator="">
<div class="cfs_true_false ready">
<span class="checkbox"></span>
<span>Is this a news item?</span>
<input type="hidden" name="cfs[input][6][value]" class="true_false" value="0">
</div>
</div>
As per your requirement.Why dont you set like this ??
$(document).ready(myfunc);
function myfunc()
{
$('.checkbox').addClass('checked');
$('.true_false').val('1');
}
if($('.checkbox').hasClass('checked'))
{
alert($('.true_false').val());
}
Click on the demo below to see that value 1 is getting set and checked class is getting set.
You can do this on click of a button or checking a checkbox.
Click Here
Try this:
Also for demo purpose, I have kept input as text instead of hidden.
Fiddle
(function(){
$(".checkbox").on("click",function(){
$(this).toggleClass("checked");
var val = 0;
val = $(this).hasClass("checked")?1:0;
$(this).parent().find(".true_false").val(val);
});
})()
.checked{
background: blue!important;
}
.checkbox{
width:20px;
background:#eee;
padding:5px;
border:1px solid black
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="field field-news_item" data-type="true_false" data-name="news_item" data-validator="">
<div class="cfs_true_false ready">
<span class="checkbox"></span>
<span>Is this a news item?</span>
<input type="text" name="cfs[input][6][value]" class="true_false" value="0">
</div>
</div>
<div class="field field-news_item" data-type="true_false" data-name="news_item" data-validator="">
<div class="cfs_true_false ready">
<span class="checkbox"></span>
<span>Is this a news item?</span>
<input type="checkbox" id="checkbox" />
<input type="text" name="cfs[input][6][value]" class="true_false" value="0">
</div>
</div>
$(document).ready(function(){
$('#checkbox').change(function(){
var checkboxValue = $(this).is(':checked');
if(checkboxValue == true){
$(".true_false").val('1');
alert('1');
}else{
$(".true_false").val('0');
alert('0');
}
});
});
Related
How can I link a radio button and a text input filled so when the radio is selected the text in the input text area will also change to lets say... red-bold?
I know the logic is:
When radio-A and input-text-A is checked, add CSS class to input-text-A.
When unchecked remove class. If radio-B is selected change input-text-B, and so on...
But right now the simple script targets all text inputs.
$('input[type=text]').addClass('red');
.red {
color: red;
font-weight: bold;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-inline">
<label class="" for="">
<input class="" type="radio" name="answer-Q1" value="option1"> A. </label>
<input type="text" name="answers" class="" placeholder="" required>
</div>
<br>
<div class="form-inline">
<label class="">
<input class="" type="radio" name="answer-Q2" value="option1"> B. </label>
<input type="text" name="answers" class="" placeholder="" required>
</div>
Give your markup, there's actually no need to add any classes or use javascript, you can do what you want with pure CSS:
input[type="radio"]:checked + input[type="text"] {
color: red;
font-weight: bold;
}
As for how to add the class with jQuery, I tend to write "robust" solutions that are maybe a bit longer, but are not as "brittle" (meaning: if markup changes a bit, the script will still work). The way I would write this - assuming no control over markup - would be using jQuery's closest and find to locate the target text inputs:
// no-conflict-save document ready shorthand
jQuery(function($) {
// bind to the "change" event of all inputs that are radio buttons
jQuery('input[type="radio"]').on('change', function() {
// find the text input
var $text_input = $(this).closest('div').find('input[type="text"]');
// if there isn't one, get out
if ( ! $text_input.length ) {
return;
}
// if the radio button is checked, add the class
if ($(this).is(':checked')) {
$text_input.addClass('red');
} else {
// otherwise, remove the class
$text_input.removeClass('red');
}
});
});
However, if I DID have control over markup, I would add a class to the radio input element, and use that to both make the script more "generically" useful, as well as narrow down the scope of which inputs were being bound (which would allow this same script to work effectively on checkboxes + text inputs as well):
// no-conflict-save document ready shorthand
jQuery(function($) {
// bind to the "change" event of any inputs with the "watch-change" class
jQuery('input.watch-change]').on('change', function() {
// find the text input. Note, this would find multiple text inputs if they existed.
var $text_input = $(this).closest('div').find('input[type="text"]');
// if there isn't a text input to work with, get out
if ( ! $text_input.length ) {
return;
}
// if the radio button is checked, add the class
if ($(this).is(':checked')) {
$text_input.addClass('red');
} else {
// otherwise, remove the class
$text_input.removeClass('red');
}
});
});
And, honestly, with a better understanding of your project scope, it might be possible to write an even more efficient, re-usable snippet of script.
Do this:
$("input[type=radio]").on("change", function(e) {
if (e.currentTarget) {
e.currentTarget.next("input[type=text").addClass("red");
}
});
Here is the working code.
$('input:radio').click(function() {
$('label:has(input:radio:checked)').addClass('rightAnswer');
$('label:has(input:radio:not(:checked))').removeClass('rightAnswer');
});
.container {margin:0 auto; margin-top:50px;}
.rightAnswer {font-weight:bold; color:#2979FF;}
.inputAnswers {width:200px;}
.block {display:block;}
input[type="radio"]:checked + input[type="text"] {
color: #2979FF;
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<label class="block" for="answer-Q1A">
<input type="radio" class="" name="answer-Q1" value="1"> A.
<input type="text" name="answers" class="inputAnswers" id="answer-Q1A" placeholder="" required></label>
<label class="block" for="answer-Q1A">
<input type="radio" class="" name="answer-Q1" value="1"> B.
<input type="text" name="answers" class="inputAnswers" id="answer-Q1A" placeholder="" required></label>
<label class="block" for="answer-Q1A">
<input type="radio" class="" name="answer-Q1" value="1"> C.
<input type="text" name="answers" class="inputAnswers" id="answer-Q2A" placeholder="" required></label>
</div>
I have an input checkbox field and when the checkbox changes (user clicks or unclicks) the div below should toggle. In my style sheet I have the div paypalInputArea as display:none and when the checkbox in clicked, it should toggle, however I can't seem to get it to work. Can anyone see what is wrong with my code?
Here is my html:
<div class="checkbox-row" id="paypalCheckbox">
<input type="checkbox" maxlength="2147483647" value="true" name="paypalPaymentCheckbox" id="paypalPaymentCheckbox" class="checkinput styled" />
<label class="paymentMethodTitle"></label>
</div>
<div class="paypalInputArea">
<isinclude template="includes/paymentmethodsinclude" />
</div>
And here is my jQuery:
$("#paypalCheckbox.checkbox-row .areaExpander").on('change', function() {
$(".paypalInputArea").toggle();
if ($('.paypalInputArea').is(':visible')) {
app.paymentAndReview.setCOContinueBtn(true);
$("#paypalPaymentCheckbox").attr('checked','true');
$('#paypalCheckbox.checkbox-row .areaExpander').addClass('open');
} else {
$("#paypalPaymentCheckbox").removeAttr('checked');
$('#paypalCheckbox.checkbox-row .areaExpander').removeClass('open');
app.paymentAndReview.setCOContinueBtn(false);
}
});
$("#paypalCheckbox.checkbox-row input").attr('checked') && app.paymentAndReview.setCOContinueBtn(true);
$("#paypalCheckbox").on('change', function() {
$(".paypalInputArea").toggle();
if ($('.paypalInputArea').is(':visible')) {
//app.paymentAndReview.setCOContinueBtn(true);
$('#paypalCheckbox.checkbox-row .areaExpander').addClass('open');
} else {
$('#paypalCheckbox.checkbox-row .areaExpander').removeClass('open');
//app.paymentAndReview.setCOContinueBtn(false);
}
});
$("#paypalCheckbox.checkbox-row input").attr('checked') && app.paymentAndReview.setCOContinueBtn(true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="checkbox-row" id="paypalCheckbox">
<input type="checkbox" maxlength="2147483647" value="true" name="paypalPaymentCheckbox" id="paypalPaymentCheckbox" class="checkinput styled" />
<label class="paymentMethodTitle"></label>
</div>
<div class="paypalInputArea" style="display:none">
blabla
</div>
just replace the line:
$("#paypalCheckbox.checkbox-row .areaExpander").on('change', function() {
with:
$("#paypalCheckbox").on('change', function() {
As you have an ID (which has to be unique) you dont have to use other classes or else to reach it!
you can also remove those lines as the attrribute checked is set as the user clicks on the checkbox
$("#paypalPaymentCheckbox").attr('checked','true');
$("#paypalPaymentCheckbox").removeAttr('checked');
Hope this helps!
It looks like you're missing the class areaExpander from your checkbox
I am trying to add a small script to an html form. All of the fields default to the string 'pass'. If a field is changed to anything other than 'pass' the text field should change it's border to red outline. If the value is edited then changed back to "pass", it should remove the border.
My example is almost working. If I change a value it turns the box red. But then if I tab to another field that has not changed it outlines THAT box in red too. It also does not change back if I set the value back to "pass". I am working on this for a Rails app, but my JS skills are pretty bad.
My form and JS.
$(document).ready(function(){
$("input").keyup(function(){
if ($(this).value !== "pass") {
$(this).css("border", "3px double red");
} else {
$(this).css("border", "0px");
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="field h4">
<label for="inspection_results_soiled">Soiled:</label>
<input id="inspection_results_soiled" type="text" name="inspection[results][soiled]" value="pass"><br>
</div>
<div class="field h4">
<label for="inspection_results_contaminated">Contaminated:</label>
<input id="inspection_results_contaminated" type="text" name="inspection[results][contaminated]" value="pass"><br>
</div>
As you can see it will change the border if you edit the default text. But then hit tab and it will outline the next box. Also it fails to change back when set back to "pass"
you should use $(this).val() as documented here
http://api.jquery.com/val/
instead of $(this).value which returns undefined resulting the behavior you are seeing.
Please use .val() instead of .value . Try below code.
$(document).ready(function(){
$("input").keyup(function(){
if ($(this).val() !== "pass") {
$(this).css("border", "3px double red");
} else {
$(this).css("border", "0px");
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="field h4">
<label for="inspection_results_soiled">Soiled:</label>
<input id="inspection_results_soiled" type="text" name="inspection[results][soiled]" value="pass"><br>
</div>
<div class="field h4">
<label for="inspection_results_contaminated">Contaminated:</label>
<input id="inspection_results_contaminated" type="text" name="inspection[results][contaminated]" value="pass"><br>
</div>
A couple of issues in your code. To fix, I did the following:
1- I used .val() instead of .value
2- I rearranged the code, basically same logic, but different order. And it worked. For me, cleaning the code makes it work and I can't really explain what I changed.
3- I put the logic in a separate function.
Here's a workign example:
$(document).ready(function() {
function borderchange($input) {
console.log($input.val());
let inputVal = $input.val();
if (inputVal === "pass") {
$input.css("border", "solid black 0px");
} else {
$input.css("border", "3px double red");
}
}
$(".inputfield").keyup(function() {
console.log($(this).val());
borderchange($(this));
})
})
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<div class="field h4">
<label for="inspection_results_soiled">Soiled:</label>
<input class="inputfield" id="inspection_results_soiled" type="text" name="inspection[results][soiled]" value="pass"><br>
</div>
<div class="field h4">
<label for="inspection_results_contaminated">Contaminated:</label>
<input class="inputfield" id="inspection_results_contaminated" type="text" name="inspection[results][contaminated]" value="pass"><br>
</div>
You can use pattern attribute set to "pass" and required attribute to match empty string, :invalid and :valid pseudo classes at CSS to set border property
:invalid {
border: 3px double red;
}
:valid {
border: none;
}
<div class="field h4">
<label for="inspection_results_soiled">Soiled:</label>
<input id="inspection_results_soiled" type="text" name="inspection[results][soiled]" value="pass" pattern="pass" required><br>
</div>
<div class="field h4">
<label for="inspection_results_contaminated">Contaminated:</label>
<input id="inspection_results_contaminated" type="text" name="inspection[results][contaminated]" value="pass" pattern="pass" required><br>
</div>
I get the following HTML of which I have no control:
<div class="form-wrap">
<div class='input-wrap' data-field='start-set'>
<input type='radio' name='participant[0][start-set][value]' value='Information centre' class='participant-form--input-radio'/>
<span>Information centre</span>
<input type='radio' name='participant[0][start-set][value]' value='Terminal' class='participant-form--input-radio'/>
<span>Terminal<span>
</div>
<div class='input-wrap' data-field='delivery'>
...
</div>
</div>
And this might be repeated multiple times in the same page, for different participants.
What needs to be done is to capture the radio input change and if the radio value is 'terminal', to display the sibling div with data-field='delivery'.
I am really bad at front end, so would appreciate any help or guidance.
You can use tree traversal#next() method
$("input[type='radio'].participant-form--input-radio").on('change', function() {
var currentRadio = $(this);
if (currentRadio.val() == "terminal") {
currentRadio.parent().next().show();
}
})
$('input[type=radio]').change(function() {
if ($(this).val() == 'Terminal') {
$(this).parents('.input-wrap').next('[data-field=delivery]').show();
} else {
$(this).parents('.input-wrap').next('[data-field=delivery]').hide();
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="form-wrap">
<div class='input-wrap' data-field='start-set'>
<input type='radio' name='participant[0][start-set][value]' value='Information centre' class='participant-form--input-radio' />
<span>Information centre</span>
<input type='radio' name='participant[0][start-set][value]' value='Terminal' class='participant-form--input-radio' />
<span>Terminal<span>
</div>
<div class='input-wrap' data-field='delivery' style="display:none;">
...
</div>
</div>
First, you'll need to bind a change event to your radio button, I've used the name starts with ... selector.
$('input[name^=participant]').on('change', function() {
Alternatives are:
$('input:radio') /* all radiobuttons */
$('.form-wrap input:radio') /* all radiobuttons inside .form-wrap */
$('.participant-form--input-radio') /* class selector */
After that we need to find the element we want to show and hide. I prefer to travel up the tree to the elements parent and the find the child we are looking for
$(this).closest('.form-wrap').find('[data-field="delivery"]')
Then I use toggle(statement) to either hide or show it. The statement in this case will be "is the value 'Terminal'"
.toggle( $(this).val() == 'Terminal' )
All together, it looks like this:
$(function() {
$('input[name^=participant]').on('change', function() {
$(this).closest('.form-wrap').find('[data-field="delivery"]').toggle( $(this).val() == 'Terminal' );
});
});
[data-field="delivery"] { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-wrap">
<div class='input-wrap' data-field='start-set'>
<input type='radio' name='participant[0][start-set][value]' value='Information centre' class='participant-form--input-radio' />
<span>Information centre</span>
<input type='radio' name='participant[0][start-set][value]' value='Terminal' class='participant-form--input-radio' />
<span>Terminal</span>
</div>
<div class='input-wrap' data-field='delivery'>
...
</div>
</div>
I am creating a form with multiple radio buttons and text boxes.
Each Text box is next to radio button like below:
<div class="form-group">
<div class="radio">
<label>
<input type="radio" name="correct_answer_id">
Correct
</label>
</div>
<label for="answer" class="col-sm-2 control-label">Answer 2</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="answer[]" placeholder="Answer" required>
</div>
</div>
There are several radio button and text box pair like above in the form.
On click of the radio button, i want to get whatever has been written in the corresponding text box
i am trying to use Jquery's next() function like below:
$('input[type="radio"]').click(function(){
if ($(this).is(':checked'))
{
console.log($(this).next('input[type="text"]').val());
}
});
But my log shows undefined. What i am doing wrong?
Try this : find parent div of radio and do next().next() to get input box div and then find input box to get value.
NOTE - You need not to check if ($(this).is(':checked')) as when you click on radio button it will get checked always.
$('input[type="radio"]').click(function(){
var value = $(this).closest('.radio').next().next('.col-sm-10').find('input[type=text]').val();
console.log(value );
});
use below code using parents(); see working fiddle
$('input[type="radio"]').click(function(){
if ($(this).is(':checked'))
{
console.log($(this).parents('div.radio').next().next('div.col-sm-10').find('input[type="text"]').val());
}
});
You should put the value that you want submitted in the value attribute of your input elements.
e.g. <input type="radio" name="correct_answer_id" value="correct">
Your click handler would change to:
$('input[type="radio"]').click(function(){
if ($(this).is(':checked'))
{
console.log($(this).val());
}
});
If there's some value that you don't want to place in the value attribute then it's still best to have a reference to the value in the input element instead of relying on a particular document layout.
Try this
$('input[type="radio"]').click(function(){
if ($(this).is(':checked'))
{
console.log($(this).parent().parent().siblings().find('input[type="text"]').val());
}
});
Working Demo
If you can change the html a little, here is a different approach http://jsfiddle.net/xa9cjLd9/1/
<div class="form-group">
<div class="radio">
<label data-for='answer[]'>
<input type="radio" name="correct_answer_id" />Correct</label>
</div>
<label for="answer" class="col-sm-2 control-label">Answer 2</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="answer[]" placeholder="Answer" required />
</div>
</div>
$('input[type="radio"]').click(function () {
if ($(this).is(':checked')) {
var data = $(this).closest('label').attr('data-for');
console.log($('input[name=' + '"' + data + '"' + ']').val());
}
});
Just Define a data attribute to the label , which contains the name of the related input.