I have 3 divs, each with a dfew input fields and next button on.
I want to write a snippet of jQuery that when the next button is clicked it checks to ensure all input fields WITHIN the same div as the button, are not null.
I've tried the following with no luck but Im 100% certain its wrong, only I cant find the relevant information online...
http://jsfiddle.net/xG2KS/1/
You could use filter to reduce the set of all input elements to only those that are empty, and check the length property of what remains:
$(".next").click(function() {
var empty = $(this).parent().find("input").filter(function() {
return this.value === "";
});
if(empty.length) {
//At least one input is empty
}
});
Note that the definition of empty in the above code is an empty string. If you want to treat blank spaces as empty too, you may want to trim the value before comparing.
Also note that there is no need to pass this into jQuery inside the filter function. The DOM element itself will have a value property, and it's much faster to access that instead of using val.
Here's an updated fiddle.
$('.next').click(function() {
var emptyInputs = $(this).parent().find('input[type="text"]').filter(function() { return $(this).val() == ""; });
if (emptyInputs.length) {
alert('Fail!');
}
});
Because there is no jQuery selector for this case you can extend jQuery’s selector capabilities.
Assuming you select all :text elements, the extension is:
$.extend($.expr[':'],{
isEmpty: function(e) {
return e.value === '';
}
});
Hence, you can select all empty text fields:
$(this).closest('div').find(':text:isEmpty');
$.extend($.expr[':'], {
isEmpty: function (e) {
return e.value === '';
}
});
$('.next').click(function () {
var missingRequired = $(this).closest('div').find(':text:isEmpty');
console.log('Empty text fields: ' + missingRequired.length);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input type="text" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="submit" value="next" class="next" />
</div>
<div>
<input type="text" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="submit" value="next" class="next" />
</div>
<div>
<input type="text" /><br />
<input type="text" /><br />
<input type="submit" value="next" class="next" />
</div>
$('.next').click(function() {
var inputs = $(this).parent().find('input[value=""]');
if (!inputs.length) {
// you have empty fields if this section is reached
}
});
Related
I'm trying to reflect data entered in one text box to another text box on checkbox tick. The default state of checkbox is checked. The value should change after it is unchecked and gets checked back again. Even though the code seems to be working, the only output I'm getting is 'on'.
$(".check").click(function() {
if ($(this).is(":checked")) {
$('.add1').val(this.value) === $('.add2').val(this.value);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type=checkbox checked class="check">
<input type="text" id="first" class="add1" />
<input type="text" id="second" class="add2" />
Kindly note that I would like to do this by class.
Here's the fiddle: https://jsfiddle.net/starscream166/n87vLd51/1/
The issue is because this refers to the checkbox. Hence this.value, which you place in the value of the textboxes, it the string 'on'.
To fix this place the val() of .add1 in to .add2, as in the below example. Also note the use of change instead of click when dealing with checkboxes, as it improves accessibility.
$(".check").change(function() {
if (this.checked) {
$('.add2').val($('.add1').val());
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" checked class="check">
<input type="text" id="first" class="add1" />
<input type="text" id="second" class="add2" />
Please check here: https://jsfiddle.net/4kp3msax/1/
OR you can do the following code.
$(".check").click(function() {
if ($(this).is(":checked")) {
var add1 = $('.add1').val();
$('.add2').val(add1);
}
});
Pass $('.add2').val() the result of $('.add1').val()
.val() can be used to retrieve or assign an input's value. It can be called without a parameter, which will return the string value of the input. Or, it can be called with a parameter which will assign the value to the input.
$(".check").click(function() {
if ($(this).is(":checked")) {
$('.add2').val($('.add1').val());
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type=checkbox checked class="check">
<input type="text" id="first" class="add1" />
<input type="text" id="second" class="add2" />
Works when any of one field data changed
let swt_data = "";
$(".add1").on("change", function() {
swt_data = $(this).val();
})
$(".check").click(function() {
if ($(this).is(":checked")) {
if (swt_data != $('#first').val() != $('#second').val()) {
$('#first').val(swt_data);
$('#second').val(swt_data)
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type=checkbox checked class="check">
<input type="text" id="first" class="add1" />
<input type="text" id="second" class="add1" />
I have 10 input fields that I want to check have at least 2 charaters in ...
<input type="text" />
<input type="text" />
<input type="text" />
$('input[type="text"]').on('keyup', function(){
if($(this).length > 2){
alert('yeah')
} else {
alert('no');
}
});
I'm using the above but I keep getting the alert "No"
Why is this?
I'd just use this.value instead of making an unnecessary jQuery object. Also using the input event will make the logic fire only if the value changes, and not for other keys like arrow keys and others that don't actually change the value.
$('input[type="text"]').on('input', function(){
console.log(this.value.trim().length > 2 ? 'yeah' : 'no');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
<input type="text" />
<input type="text" />
$(this) refers to jQuery object, not element's value. You need to get the value first via $.val() method.
Do it like this:
if ($(this).val().length > 2) { ... }
http://api.jquery.com/val/
Or as #Taplar suggested, you can simply access the this.value property (this will refer to the first matched element). This way you can speed up the code a little bit because you will not create new jQuery object instance.
if (this.value.length > 2) { ... }
$('input[type="text"]').on('keyup', function(){
if($(this).val().length > 2){
console.log('yeah')
} else {
console.log('no');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
<input type="text" />
<input type="text" />
I have an ASPX form and I need to disable the submit button if any one of six specific fields are empty. I'm trying to do this via Javascript or jQuery, but so far I can only find examples of either a single field on the form being empty, or ALL fields on the form. In my case, I don't care about several fields - only the six specific ones.
So basically, I have six conditions and one action. I found one example, but it was stringing together six different IF statements. I'd like to find a more streamlined way if possible. So, for example, I might do THIS for a single field... but how to do it for field2, field3, field4, etc. as well?
$(document).ready(function(){
$('#submit_btn').prop('disabled',true);
$('#field1').keyup(function(){
$('#submit_btn').prop('disabled');
})
});
Using Javascript or jQuery, what's the most efficient way to disable an input button if any of six input fields is blank?
You can add the same class name to all the elements and then do a validation foreach class element. Like in below code, i added the same class name to all the input for which the validation is required using class="valid" and then use the jquery class selector and the keyup method that you used to control the state of the button.
(function() {
$('.valid').keyup(function() {
var isEmpty = false;
$('.valid').each(function() {
if ($(this).val() == '') {
isEmpty = true;
}
});
if (isEmpty) {
$('#button1').attr('disabled', 'disabled');
} else {
$('#button1').removeAttr('disabled');
}
});
})()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
1<input type="text" class="valid" /><br />
2<input type="text" class="valid" /><br />
3<input type="text" class="valid" /><br />
4<input type="text" class="valid" /><br />
5<input type="text" class="valid" /><br />
6<input type="text" class="valid" /><br />
<input type="button" id="button1" value="Test Me!" disabled="disabled" />
</form>
If your requirements will allow it, you can use HTML 5 field validation. The browser will not allow the form to submit.
<form>
<label for="choose">Foo</label>
<input name="bar" required>
<input type="submit" /> <!-- <--- This will generate an error message if the user clicks it when the field is empty -->
</form>
You have the start of it correct; create an array with six variables, one for each of the fields, and create a new function to validate everything that is called on each keyup. So you would have
var[] array
$('#field1').keyup(function() {
array[0] = $('#field1').val();
validate();
}
${'#field2').keyup(function() {
array[1] = $('#field2').val();
validate();
}
...create one each for each field
function validate() {
for (var i = 0; i < array.length; i++) {
if(!arrays[i]) {
$('#submit_btn').prop('disabled');
return;
}
}
$('#submit_btn').prop('enabled'):
}
What this does is it listens to the fields for changes and updates the array. A blank value is falsy so you can just go through the array and disable the button if it's blank or null or something. Break out of the for loop in that case; you don't care about whatever else. If nothing disables the button and breaks the for loop then it's valid and the button is enabled.
This approach is useful because it's easily extendable. You can just push extra things into the array if you want to check them without rewriting the validation function.
This assumes you do not want to just use standard form validation and do it manually.
Add a common class to each of the required inputs. Then check the length of that object against the length of a filtered object where value is not empty. Then you can use that condition to set the prop value of the button to true/false.
http://api.jquery.com/filter/
JQuery:
$('form .required-valid').on('input paste change', function() {
var $required = $('form .required-valid');
//filter required inputs to only ones that have a value.
var $valid = $required.filter(function() {
return this.value != '';
});
//set disabled prop to false if valid input count is != required input count
$('#submit_btn').prop('disabled', $valid.length != $required.length);
});
HTML:
<form>
<label>Field1</label>
<input type="text" id="field1" class="required-valid" />
<label>Field2</label>
<input type="text" id="field2" class="required-valid" />
<label>Field3</label>
<input type="text" id="field3" class="required-valid" />
<label>Field4</label>
<input type="text" id="field4" class="required-valid" />
<label>Field5</label>
<input type="text" id="field5" class="required-valid" />
<label>Field6</label>
<input type="text" id="field6" class="required-valid" />
<label>Field7</label>
<input type="text" id="field7" class="not-required" placeholder="not required" />
<button id="submit_btn" disabled>
Submit
</button>
</form>
Example:
https://jsfiddle.net/SeanWessell/q2msc80L/
$(document).ready(function() {
$('#submit_btn').prop('disabled', true);
$('#field1').keyup(function() { // on keyup
var value = $(this).val(); // retrieve the value of the input
if (value.length == 0) // if the value's length is 0 (empty)
$('#submit_btn').prop('disabled', true); // disable the button
else // if not
$('#submit_btn').prop('disabled', false); // enable it
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input id="field1"/>
<input id="submit_btn" type="submit"/>
</form>
Just note that the form can be submitted using enter key, so instead of checking on every keyup, it would be better if you check onsubmit instead.
I am new to web development and I am trying to create a simple form validation using javascript/jquery.
I drafted a simple form very similar to what I have that looks like this:
<form>
<input class="price" type="text" />
<br />
<input class="price" type="text" />
<br />
<input class="price" type="text" />
<br />
<input class="price" type="text" />
<br />
<button type="submit" onclick='return validateSubmit();'>Save</button>
</form>
What I want to happen is when the user clicks the submit button, it will check every input box if it contains a valid number (price) before it allows the submit, if one or more of the input box is invalid, it will be highlighted with an alert error "Invalid inputs on highlighted textboxes" or something like that. After couple of searches this is what I have in my script:
var validateSubmit = function () {
var inputs = $('.price');
var errors = 'False';
for (var i = 0; i < inputs.length; i++) {
if (isNaN(inputs[i].value)) {
$('.price')[i].focus();
}
errors = 'True';
}
if (errors == 'True') {
alert('Errors are highlighted!');
return false;
}
return true;
};
I understand what is wrong with what Ive done but I dont know how to fix it.
I know that we can only focus() 1 element at a time but I wanted to have some effect that it highlights the inputboxes with invalid characters.
Please tell me how to do it or if there's a better approach can you show me some examples. I saw bootstrap has some css effects for this focus but I dont know how to implement it. Thank you!
You can add a class to the inputs with bad values. The class can add a border for example.
var validateSubmit = function () {
var inputs = $('.price');
var errors = 'False';
for (var i = 0; i < inputs.length; i++) {
if (isNaN(inputs[i].value)) {
$(inputs[i]).addClass('error');
errors = 'True';
} else {
$(inputs[i]).removeClass('error');
}
}
if (errors == 'True') {
alert('Errors are highlighted!');
return false;
}
return true;
};
.error {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input class="price" type="text" />
<br />
<input class="price" type="text" />
<br />
<input class="price" type="text" />
<br />
<input class="price" type="text" />
<br />
<button type="submit" onclick='return validateSubmit();'>Save</button>
</form>
First, I think you should clean up your HTML. For example, it is always a good idea to give an id attribute to your form tags to reference them. Also, someone correct me if I am wrong, you won't be submitting any values without giving a name attribute to your input fields.
<form id="price-form" action="" method="get">
<input name="price[]" type="text" value="" class="price" />
<br />
<input name="price[]" type="text" value="" class="price" />
<br />
<input name="price[]" type="text" value="" class="price" />
<br />
<input name="price[]" type="text" value="" class="price" />
<br />
<button type="submit">Save</button>
</form>
Now, since you are using jQuery, why not utilize its methods such as on() and .each() ?
$(function() {
$('#price-form').on('submit', function(e) {
// this variable acts as a boolean, so might as well treat it as a boolean
var errors = false;
// remove previous errors
$('.price').removeClass('error');
// check each input for errors
$('.price').each(function() {
if (isNaN(this.value)) {
$(this).addClass('error');
errors = true;
}
});
// alert if there are any errors
if (errors) {
alert('Errors are highlighted!');
e.preventDefault(); // stop submission
}
});
});
In your CSS, you could do
.error {
border: 2px solid #a00;
}
The problem: I have a page with many <input> fields (just say all are text fields)
I would like to have a button, when click on it, all input fields will become plaintext only.
e.g. <input type="text" value="123" /> becomes 123
and if I click on another button, the text will change back to
e.g. 123 becomes <input type="text" value="123" />
Is there an automatic way to scan for all the <input>s and change them all at once using javascript and jquery.
Thank you!
Edited
Seems you guys are getting the wrong idea.
Read what I have written again: e.g. <input type="text" value="123" /> becomes 123
I have value="123" already, why would I want to set the value again???
What I want is e.g.
<body><input type="text" value="123" /><input type="text" value="456" /></body> becomes <body>123456</body> and later <body>123456</body> back to <body><input type="text" value="123" /><input type="text" value="456" /></body>
Use this to go one way,
$('input').replaceWith(function(){
return $('<div />').text(this.value).addClass('plain-text');
});
and this to go the other.
$('.plain-text').replaceWith(function(){
return $('<input />').val($(this).text());
});
Check this link http://jsfiddle.net/Evmkf/2/
HTML:
<div id='divInput'>
<input type="text" value='123' />
<br/>
<input type="text" value='456' />
<br/>
<input type="text" value='789' />
</div>
<div id='plainText' style='display:none'></div>
<div>
<input type="button" id='btnPlain' value='Make It Plain' />
<input type="button" id='btnInput' value='Make It Text' />
</div>
Javascript:
$("#btnPlain").bind('click',function(){
$("#plainText").html('');
$("#divInput input[type=text]").each(function(index){
$("#plainText").append('<span>'+$(this).val()+'</span>');
$("#divInput").hide();
$("#plainText").show();
});
});
$("#btnInput").bind('click',function(){
$("#divInput").html('');
$("#plainText span").each(function(index){
$("#divInput").append('<input type="text" value="'+$(this).text()+'"/><br/>');
$("#plainText").hide();
$("#divInput").show();
});
});
Try this FIDDLE
$(function() {
var arr = [];
$('#btn').on('click', function() {
var $text = $('#inp input[type="text"]');
if( $text.length > 0){
$text.each(function(i) {
arr[i] = this.value;
});
$('#inp').html(arr.join());
}
else{
if(arr.length <= 0){
}
else{ // Add Inputs here
var html = '';
$.each(arr, function(i){
html += '<input type="text" value="' + arr[i]+ '"/>'
});
$('#inp').html(html);
}
}
});
});
You need to create a hidden element for each input, then use jquery to hide the input, show the hidden element and give it the inputs value.
<input type="text" value="123" id="input_1" />
<div id="div_1" style="display:none;"></div>
$("#div_1").html($("input_1").val());
$("#input_1").hide();
$("#div_1").show();