jQuery - How do I use AND with Selector? - javascript

My code's function is to alert user if the ptype textfield is empty.
$("input[name*='ptype']").each(function() {
if ($(this).val() == "") {
$(this).css({'background-color' : '#feffe3'});
e.preventDefault();
alert("Enter Value!");
}
});
However, I need to add another criteria where another field amount is not 0. So that the function get triggered when ptype="" && amount!=0. I'm very new in jQuery, and I'm not sure how to use AND operator in here. I've tried to do some based on other questions but it seems not working.
$("input[name*='ptype'][amount!='0']").each(function() {
$("input[name*='ptype'] , [amount!='0']").each(function() {
What am I missing ?

You can do it with && sign. Code depends on where your amount field is located and what it is. If I guess right it should be something like this:
$("input[name*='ptype']").each(function() {
if ($(this).val() == "" && $(this).parent().find(input[name='amount']).val() != 0) {
$(this).css({'background-color' : '#feffe3'});
e.preventDefault();
alert("Enter Value!");
}
});

That code $("input[name*='ptype'][amount!='0']").each(function() { is valid. You have to check the CSS selectors list.
The problem maybe in your *= selection. input[name*="ptype"] means Selects every element whose name attribute value contains the substring "ptype".
$('input[name*="ptype"][amount!="0"]').each(function() {
if ($(this).val() == "") {
$(this).css({'background-color' : '#feffe3'});
e.preventDefault();
alert("Enter Value!");
}
});
Take a look at this test https://jsfiddle.net/xpvt214o/211871/

« where another field» is the key in question.
So you need a selector to check if a selected element is empty and another element is not zero.
Holà!
Logic problem here.
with $(selector) you can look up for some elements.
There is no AND / OR in selectors for many sets of matching element.
A selector is ONE set of matching elements.
No way this selector can check for an attribute value of another set.
So you have to know your markup and navigate a bit... And take care of variable types.
$("input[name*='ptype']").each(function() {
if ( parseInt( $(this).next("input").val() ) != 0) {
$(this).css({"background-color" : "red"});
alert("Enter Value!");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
ptype: <input type="text" name="ptype"><br>
amount: <input type="text" name="amount" value="1">
You have to look for another element's value here, from my understanding. So you have to know what is that "other" element and the methods to use may vary a lot depending on your HTML...

You can use this function in your button.
function check(e){
var verror = false;
$("input[name*='ptype']").each(function(index, value) {
var amount = $($("input[name='amount[]']").get(index)).val();
var ptype = $(this).val();
if(ptype.length <= 0 && amount.length > 0 ){
verror = true;
$(this).focus();
return false;
}
});
if(verror){
e.preventDefault();
alert("Enter Value!");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
ptype: <input type="text" name="ptype[]">
amount: <input type="text" name="amount[]" value="1"> <br>
ptype: <input type="text" name="ptype[]">
amount: <input type="text" name="amount[]" value="2"> <br>
<button type="button" onclick="check(event)">Click</button>
</form>

Related

JavaScript - Looping through elements and checking for length

I have some code that goes through the elements that end in '_ro' as below:
document.querySelectorAll("[id$=_ro]").forEach(function(element) {
element.readOnly = true;
});
Is there a way I can check to see if there is an input, and if there is a value input, set it to read only?
Try element.nodeName == 'INPUT' to check the node name and element.value.length to check the value length:
document.querySelectorAll("[id$=_ro]").forEach(function(element) {
if(element.nodeName == 'INPUT' && element.value.length)
element.readOnly = true;
});
<input id="name_ro" type="text" value="Jhon"/>
<div id="div_ro">test</div>
<input id="phone_ro" type="text"/>

Jquery Unfocus field if value equals

What I am trying to achieve in the below code is when "0" has been entered into the input field it gets unfocused and other stuff triggers.
$(".val-0").keyup(function() {
if ($(this).val() === 0) {
$(this).blur();
// Do other Stuffss
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input class="val-0" type="number">
You are missing an opening quotation on the class name, for one thing.
For another, you are using === to compare which requires same data type (strict comparison). input.val() returns data of type string not integer.
Deeper explanation here.
You want to compare using $(this).val() == 0) or $(this).val() === '0')
$(".val-0").keyup(function() {
if ($(this).val() == 0) {
$(this).blur();
// Do other Stuffss
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input class="val-0" type="number">
Due to some reason you cannot attached keyup event to input type of number. I tried to put working example here. I hope it will help you.
$(".val-0").keyup(function(event) {
console.log(event.which + ", " + $(this).val());
if ($(this).val() === 0) {
$(this).blur();
console.log($(this));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="val-0" type="text" />

Error when taking the length of an input

I want to use .length in this script, but when I add .length, the script fails.
The input:
<input type="text" name="myform" class="myform" placeholder="Full Name" value="" maxlength="20" minlength="6" pattern="[a-zA-Z-']+.{6,40}">
Original (working) code :
if ($.trim($("input[name=myform]").val()) === "") {
$("input[name=myform]").addClass("merror");
return false;
}
});
$("input").change(function() {
$(this).removeClass("merror");
}).trigger("change");
After adding .length:
if ($.trim($("input[name=myform]").length === 6)) {
$("input[name=myform]").addClass("merror");
return false;
}
$("input").change(function() {
$(this).removeClass("merror");
}).trigger("change");
You've misplaced a ) or two.
Adding some space to your if statement shows the problem:
if ($.trim(
$("input[name=myform]").length === 6)
) {
You need a closing ). But even then, you're taking the length of $("input[name=myform]") -- which is the list of inputs with the name "myform". It will certainly be 1.
You want to take the length of the value of that input (after trimming), like so:
if ($.trim( $("input[name=myform]").val() ).length === 6)
{

How to validate if textbox value is empty in a series of textboxes?

There are a series of textboxes like:
<input type="text" class="jq-textBox" />
<input type="text" class="jq-textBox" />
<input type="text" class="jq-textBox" />
<input type="text" class="jq-textBox" />
<input type="text" class="jq-textBox" />
User can fill up the textbox values from top to bottom order. Only first textbox is required and all other textboxes are optional.
Allowed order to fill textbox values:
1st
1st & 2nd
1st, 2nd & 3rd
and likewise in sequence order
Dis-allowed order:
2nd
1st & 3rd
1st, 2nd & 4th
This means that user needs to fill up the first textbox only or can fill up the other textboxes in sequential order. User can NOT skip one textbox and then fillup the next one.
How to validate this in javascript/jQuery?
Any help is highly appreciated!
I would personaly use the disabled html attribute.
See this jsFiddle Demo
html
<form>
<input type="text" class="jq-textBox" required="required" />
<input type="text" class="jq-textBox" disabled="disabled" />
<input type="text" class="jq-textBox" disabled="disabled" />
<input type="text" class="jq-textBox" disabled="disabled" />
<input type="text" class="jq-textBox" disabled="disabled" />
<input type="submit" />
</form>
(Note the required attribute for HTML5)
jquery
$('input.jq-textBox').on('keyup', function(){
var next = $(this).next('input.jq-textBox');
if (next.length) {
if ($.trim($(this).val()) != '') next.removeAttr('disabled');
else {
var nextAll = $(this).nextAll('input.jq-textBox');
nextAll.attr('disabled', 'disbaled');
nextAll.val('');
}
}
})
Also see nextAll() jquery Method
Edit :
If you want to hide the disabled inputs in order to show them only when the previous input is filled, just add this css :
input[disabled] {
display: none;
}
Demo
You can iterate over the list backwards to quickly figure out whether there is a gap.
var last = false,
list = $(".jq-textBox").get().reverse();
$.each(list, function (idx) {
if ($(this).val() !== "") {
last = true;
}
else if (last) {
alert("you skipped one");
}
else if (list.length === idx + 1) {
alert("must enter 1");
}
});
http://jsfiddle.net/rnRPA/1/
Try
var flag = false, valid = true;
$('.jq-textBox').each(function(){
var value = $.trim(this.value);
if(flag && value.length !=0){
valid = false;
return false;
}
if(value.length == 0){
flag = true;
}
});
if(!valid){
console.log('invalid')
}
Demo: Fiddle
You can find all inputs that are invalid (filled in before the previous input) this way:
function invalidFields() {
return $('.jq-textBox')
.filter(function(){ return !$(this).val(); })
.next('.jq-textBox')
.filter(function(){ return $(this).val(); });
}
You can then test for validity:
if (invalidFields().length) {
// invalid
}
You can modify invalid fields:
invalidFields().addClass('invalid');
To make the first field required, just add the HTML attribute required to it.
I think a more elegant solution would be to only display the first textbox, and then reveal the second once there is some input in the first, and then so on (when they type in the second, reveal the third). You could combine this with other solutions for testing the textboxes.
To ensure the data is entered into the input elements in the correct order, you can set up a system which modifies the disabled and readonly states accordingly:
/* Disable all but the first textbox. */
$('input.jq-textBox').not(':first').prop('disabled', true);
/* Detect when the textbox content changes. */
$('body').on('blur', 'input.jq-textBox', function() {
var
$this = $(this)
;
/* If the content of the textbox has been cleared, disable this text
* box and enable the previous one. */
if (this.value === '') {
$this.prop('disabled', true);
$this.prev().prop('readonly', false);
return;
}
/* If this isn't the last text box, set it to readonly. */
if(!$this.is(':last'))
$this.prop('readonly', true);
/* Enable the next text box. */
$this.next().prop('disabled', false);
});
JSFiddle demo.
With this a user is forced to enter more than an empty string into an input field before the next input is essentially "unlocked". They can't then go back and clear the content of a previous input field as this will now be set to readonly, and can only be accessed if all following inputs are also cleared.
JS
var prevEmpty = false;
var validated = true;
$(".jq-textBox").each(function(){
if($(this).val() == ""){
prevEmpty = true;
}else if($(this).val() != "" && !prevEmpty){
console.log("nextOne");
}else{
validated = false;
return false;
}
});
if(validated)
alert("ok");
else
alert("ERROR");
FIDDLE
http://jsfiddle.net/Wdjzb/1/
Perhaps something like this:
var $all = $('.jq-textBox'),
$empty = $all.filter(function() { return 0 === $.trim(this.value).length; }),
valid = $empty.length === 0
|| $empty.length != $all.length
&& $all.index($empty.first()) + $empty.length === $all.length;
// do something depending on whether valid is true or false
Demo: http://jsfiddle.net/3UzHf/ (thanks to Arun P Johny for the starting fiddle).
That is, if the index of the first empty item plus the total number of empties adds up to the total number of items then all the empties must be at the end.
This is what you need :
http://jsfiddle.net/crew1251/jCMhx/
html:
<input type="text" class="jq-textBox" /><br />
<input type="text" class="jq-textBox" disabled/><br />
<input type="text" class="jq-textBox" disabled/><br />
<input type="text" class="jq-textBox" disabled/><br />
<input type="text" class="jq-textBox" disabled/>
js:
$(document).on('keyup', '.jq-textBox:first', function () {
$input = $(this);
if ($input.val()!='')
{
$('input').prop('disabled',false);
}
else {
$('input:not(:first)').prop('disabled',true);
}
});
var checkEmpty = function ()
{
var formInvalid = false;
$('#MyForm').each(function () {
if ($(this).val() === '') {
formInvalid = true;
}
});
if (formInvalid) {
alert('One or more fields are empty. Please fill up all fields');
return false;
}
else
return true;
}

Calculation issue With JQuery

I know it is very simple.But Still it is not working.I am multiplying a input number with a fixed number,but is not showing the expected result.it always shows the Error message "Please enter some value" even i enter some integer e.g. 6.
This is Html Code.
<input type="text" class="cc" id="getdata" />
<div id="result"> <input type="text" id="show" /></div>
<input type="button" value="calculate" id="calculate" />
This is JQuery Code.
$(document).ready(function () {
$("#calculate").click(function () {
if ($("#input").val() != '' && $("#input").val() != undefined) {
$("#result").html("total value is::" + parseInt($("#input").val()) * 5);
}
else {
$("#result").html("Please enter some value");
}
});
});
Any help will be highly appreciated.
Can anyone tell me please how to concatenate all clicked values of different buttons in a textbox?I want to show previous and current clicked value of button in a textbox.
Thank you.
Do you not mean #getdata? Where is #input?
Replace ("#input") with ("#getdata") in your code.
Check out this fiddle.
$(document).ready(function () {
$("#calculate").click(function () {
if ($("#getdata").val() != '' && $("#getdata").val() != undefined) {
$("#result").html("total value is::" + parseInt($("#getdata").val()) * 5);
} else {
$("#result").html("Please enter some value");
}
});
});​
You have no input whose id is "input". The jquery selector #somestring is looking for an element whose id is somestring.
Replace ("#input") by ("#getdata") in your code.
There is no field with the ID input in the HTML you posted, yet your jQuery is looking for one. Perhaps you meant $('#show')
With jQuery issues, ALWAYS suspect the selector before even wondering what else might be wrong. Confirm it actually finds the elements you think it does - never assume.
console.log($('#input').length); //0
if ($("#input").val() != '' && $("#input").val() != undefined) {
You dont have any field anywhere in your markup with the id input!
I think you intended all the instances of #input in that script to be #getdata, but you should also only read its value once into a variable and use that:
$("#calculate").click(function () {
var val = $('#getdata').val();
if (val != '' && val != undefined) {
$("#result").html("total value is::" + parseInt(val) * 5);
}
else {
$("#result").html("Please enter some value");
}
});
Live example: http://jsfiddle.net/82pf4/
$(document).ready(function () {
$("#calculate").click(function () {
if ($("#getdata").val() != '' && $("#getdata").val() != undefined) {
$("#result").html("total value is::" + parseInt($("#getdata").val()) * 5);
}
else {
$("#result").html("Please enter some value");
}
});
});
Checkout this Fiddle
I think that is what you want.
<input type="text" class="cc" id="getdata" />
<input type="button" value="calculate" id="calculate" />
<div id="result"></div>​
<script>
$("#calculate").click(calculate);
$("#getdata").keypress(function(ev){
if(ev.keyCode == 13)
calculate();
});
function calculate()
{
var $getData = $("#getdata");
var $result= $("#result");
if ($getData .val() != '' && $getData .val() != undefined && !isNaN($getData .val()))
{
$result.append((parseInt($getData .val()) * 5) + "<p>");
}
else
{
$result.append("Please enter some value<p>");
}
$getData .val("").focus();
}
​
</script>

Categories