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>
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 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');
}
});
});
Relatively new to html coding, and very new with javascript. On this page, I don't want the option to email an editor to become visible until a tripID is filled in (but form not submitted yet). Here is the form so far without that option added yet:
TripID:
<input type='text' id='atripid' name='atripid' size='6' maxlength='6' /><br><br>
Port:
<input type='text' id='aport' name='aport' size='6' maxlength='6' /><br><br>
<div id=acheckbox><br> E-mail editor? </b>
<input type='checkbox' name='acheck' onchange='copyTextValue(this);'/><br>
<div id='div' style='display:none'>
<br> <b>Subject:</b> <input type='text' id='asubject' name='asubject' size='70' maxlength='75'/><br><br>
<textarea name='aemailbody' cols='85' rows = '10'>Explain any packaging or labeling mistakes here...</textarea>
</div>
</div>
<script>
function copyTextValue(bf) {
if(bf.checked){
document.getElementById('div').style.display = 'block';
var atext = 'Frozen Sample Error Notice: '+ document.getElementById('atripid').value;
}else{
document.getElementById('div').style.display = 'none';
var atext = '';
}
document.getElementById('asubject').value = atext
}
</script>
</div>
Now to hide the email editor option until tripid is filled in, I got something like this to work on jfiddle:
<form action="">
tripid:<input type="atripid" id="atripid" value="">
port:<input type="aport" id="aport" value="">
</form>
<div id="acheckbox" style="display:none">
<br><br><br>
This is where the email options (subject and textbox) would appear.
</div>
<script>
$("#atripid").keyup(function(){
if($(this).val()) {
$("#acheckbox").show();
} else {
$("#acheckbox").hide();
}
});
</script>
But for some weird reason, it won't work anywhere else, so I can't figure out how to incorporate it into what I already have. Does anyone have any ideas that could help me? Thanks!
You can do something like this with pure javascript:
<input type="atripid" id="atripid" value="" onkeyup="keyupFunction()">
And define your keyupFunction().
See jsfiddle
The code you attempted on jsfiddle requires that you import jquery.js files. An alternate way of doung what you intend to do is
<input type='text' id='atripid' name='atripid' size='6' maxlength='6' onkeyup="toggleCheckBox(this)" />
<input type='checkbox' name='acheck' id="acheckbox" style="display:none;" onchange='copyTextValue(this);'/>
with js
function toggleCheckBox(element) {
if(element.value=='') {
document.getElementById('acheckbox').style.display = 'none';
}
else {
document.getElementById('acheckbox').style.display = 'block';
}
}
The issue is the .keyup() method, which is not consistent across browsers and does not account for other means of user input. You would rather, use an Immediately Invoked Function Expression (IIFE) that will detect the propertychange of the input field in question and then to fire the desired event if the condition is met. But for the purposes of simplicity, and the fact that I'm not as well versed enough in IIFE syntax, simply bind some events to the input field, like so:
$("#atripid").on("keyup change propertychange input paste", (function(e) {
if ($(this).val() === "") {
$("#acheckbox").hide();
} else {
$("#acheckbox").show();
}
}));
#acheckbox {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form action="">
tripid:
<input type="atripid" id="atripid" value="">port:
<input type="aport" id="aport" value="">
</form>
<div id="acheckbox">
<br>
<br>
<br>This is where the email options (subject and textbox) would appear.
</div>
I want my input always has value so that focus is fixed to it until the values are typed and the cursor also can't escape the input.
I know the focus() function is existed but how can i deal with it? It is just an event isn't it? Is there any solution?
This is the html code which include the input.
<div class="col-xs-3 vcenter from-group" id="info">
<div class="form-group">
<label class="control-label" for="inputID">아이디</label><p style="display:inline; padding-left:60px; color:red; font-size: 12px">* 적어도 하나의 대문자, 소문자, 숫자를 포함한 6자~16자</p>
<div class="controls">
<input type="text" class="form-control" name="inputID" id="inputID" placeholder="내용을 입력해 주세요" required autofocus>
</div>
</div>
This is the script where the input is bound the events.
<script>
jQuery('#inputID').keyup(blank_special_char_validation);
jQuery('#inputID').focusout(function(){
if (!$(this).val()) {
var message = "no id";
error(this.id, message); // ** TODO : SET FOCUS HERE !!
} else {
id_form_validation(this.id);
}
});
Could you guys see the **TODO in code above? I want to add function that the focus is fixed until the value is written.
Please could guys give me some idea. Thank you.
=========================================================================
I want to focus my input depends on situation. For example, I want to focus it when the value isn't existed or the validation doesn't correct. However it has to focus out when the value is existed or the validation is true.
I can set focus it finally but how can i unfocus it? I mean i want to untrigger the focus event.
jQuery('#inputID').on('blur',function(){
if (!$(this).val()) {
var message = "아이디를 입력해 주세요";
error(this.id, message);
$(this).focus();
} else {
//$(this).focus();
if (!id_form_validation(this.id)) {
$(this).focus(); // TODO : FOCUS
}else {
$(this).off('focus'); // TODO : FOCUS OUT
$(this).off('blur');
}
}
});
You can use this code to do the same... I have used blur
//jQuery('#inputID').keyup(blank_special_char_validation);
jQuery('#inputID').focusout(function() {
if (!$(this).val()) {
$(this).focus();
var message = "no id";
error(this.id, message);
}else {
id_form_validation(this.id);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-xs-3 vcenter from-group" id="info">
<div class="form-group">
<label class="control-label" for="inputID">아이디</label><p style="display:inline; padding-left:60px; color:red; font-size: 12px">* 적어도 하나의 대문자, 소문자, 숫자를 포함한 6자~16자</p>
<div class="controls">
<input type="text" class="form-control" name="inputID" id="inputID" placeholder="내용을 입력해 주세요" required autofocus>
</div>
</div>
Use $(this).focus() to focus your input.
focus() with no arguments will trigger that event on an element.
I'm trying to check whether a check box is checked, and if it is checked, then I want to add the "required" attribute to an adjacent text field. I've tried it two different ways with no success. Here are the form elements and my two JQuery attempts.
neither of those will actually trigger the event. My browser either does nothing at all or triggers an "Empty string passed to getElementById()." event
Form elements:
<div class="col-sm-5">
<label id="checkboxNumber-label" class="toplabel" for="checkboxNumber">Checkbox</label>
<g:textField name="checkboxNumber" value="${...checkboxNumber}" class="form-control" required="" aria-labelledby="checkboxNumber-label"/>
<label class="checkbox-inline">
<g:checkBox name="checkboxYesNo" id="checkboxYesNo" value="${...checkboxYesNo}" onclick="chkboxYesChecked()"/>
</label>
</div>
<div class="col-sm-5">
<label id="someTextField-label" class="toplabel" for="someTextField">Some Text Field Here</label>
<g:textField name="someTextField" id="someTextField" value="${...someTextField}" class="form-control" aria-labelledby="someTextField-label"/>
</div>
JQuery:
function chkboxYesChecked(){
if($('#checkboxYesNo').prop('checked')){
$('#someTextField').prop('required',true);
$('#someTextField').append('<span class="required-indicator">*</span>');
}else{
$('#someTextField').removeAttr('required');
}
}
$(document).ready(function() {
$('#checkboxYesNo').click(function() {
if($(this).is(":checked"))
{
$('#someTextField').prop('required',true);
$('#someTextField').append('<span class="required-indicator">*</span>');
} else {
$('#someTextField').removeAttr('required');
}
});
});
With your markup this becomes more convoluted than it needs to be.
$(document).on("click", ".checkbox-inline :checkbox", function () {
var $nextTextbox = $(this).closest("div").next("div").find(":text").first();
if (this.checked) {
$nextTextbox.prop("required", true).after('<span class="required-indicator">*</span>');
} else {
$nextTextbox.prop("required", false).next('.required-indicator').remove();
}
});
Notes
This approach uses event delegation.
There are no IDs involved, because I suppose you need the same thing more than once on your page. Tying it to a specific element ID is counter-productive.
This approach relies on the specific document structure from your sample Grails template. If you want something more flexible and easier-to-read, change your HTML.
This applies to all checkboxes that have a text field in the immediately following <div>. Use CSS classes on your elements to filter it/make it apply to specific ones only.
If there is no immediately following <div> with a text box, the function does nothing.
$(this).is(":checked") is superfluous. You don't need jQuery to find out if the current DOM element is checked. this.checked is a lot simpler and has the same effect.
Don't use inline event handlers (onclick="..."). Ever.
See it in action:
$(document).on("click", ".checkbox-inline :checkbox", function () {
var $nextTextbox = $(this).closest("div").next("div").find(":text").first();
if (this.checked) {
$nextTextbox.prop("required", true).after('<span class="required-indicator">*</span>');
} else {
$nextTextbox.prop("required", false).next('.required-indicator').remove();
}
});
input[required] {
background-color: #FFD1D1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-5">
<label id="checkboxNumber-label" class="toplabel" for="checkboxNumber">Checkbox</label>
<input type="text" name="checkboxNumber" value="${...checkboxNumber}" class="form-control" required="" aria-labelledby="checkboxNumber-label" />
<label class="checkbox-inline">
<input type="checkbox" name="checkboxYesNo" id="checkboxYesNo" value="${...checkboxYesNo}" />
</label>
</div>
<div class="col-sm-5">
<label id="someTextField-label" class="toplabel" for="someTextField">Some Text Field Here</label>
<input type="text" name="someTextField" id="someTextField" value="${...someTextField}" class="form-control" aria-labelledby="someTextField-label" />
</div>