Javascript loop with dynamic jquery val() not being picked up - javascript

I'm trying to pick out the value of an input box using jquery.
No probs there
$('#id_of_my_input_box_1').val();
But I need several so decided to put them into a loop:
============
var config_total_instances = '==some value='
for (var x = 1; x <= config_total_instances; x++) {
if (isset($('#id_of_my_input_box_'+x).val())) {
alert($('#id_of_my_input_box_'+x).val());
}
}
============
If I submit the form and I've got say 10 input boxes, the code above doesn't alert a value if the relevant input box has value.
I'm using a function below to check for values.
============
function isset(my_variable) {
if (my_variable == null || my_variable == '' || my_variable == undefined)
return false;
else
return true;
}
============
Am I missing something vital..? :-(
Addition: I shoudl add that I'm askign why I don't get the value of
$('#id_of_my_input_box_'+x).val()
echoed out in my alert box

Extending #Faber75's answer. You can set a class name for all your text element and then use something like this
$("input:text.clsname").each(function(){
if (isset(this.value)) {
alert(this.value);
}
});
In your current code if you are assigning a string to config_total_instances then it will not work.

don't consider my message an answer, more of a tip.
For a simplier code you could consider adding a class to the textboxes you need to check.
For example adding to all the inputs you need to check the class="sample" you could the use the jquery selector $(".sample") , returning you all the items and then you could simply do
$(".sample").length to count the items and $(".sample")[0].val() (or similar) to get/test values.
Cheers

Have you tried this? (note that there are three =)
if (my_variable === null || my_variable == '' || my_variable === undefined)
As an alternative to this try
if (typeof(my_variable) == 'null' || my_variable == '' || typeof(my_variable) == 'undefined')

Maybe I'm misunderstanding, but can't you just get all the <input>'s in a <form> that aren't :empty if that's the end goal of what you're trying to accomplish?
$('form#some_id input:not(:empty)').each(function () {
// do something with $(this).val() now that you have
// all the non-empty <input> boxes?
});
Or if you're just trying to tell if the user left some <input> blank, something like:
$('form#some_id').submit(function (e) {
if ($(this).find('input[type="radio"]:not(:checked), input[type="text"][value=""], select:not(:selected), textarea:empty').length > 0) {
e.preventDefault(); // stops the form from posting, do whatever else you want
}
});
http://api.jquery.com/category/selectors/form-selectors/

Related

JavaScript if-elseif-statement

In PHP, the different if-elseif-scenarios rule each other out, right? I am a little confused, I don't seem to figure out why this is not the case in JavaScript here. Can anybody tell me how to simplify this?
(This statement is connected to radio-buttons and is supposed to style the selected radio button differently. However, when I do not include all the remove-parts, clicking one and then another one leaves me with both of them styled as "selected")
$("#item-upload-form input").on("change", function() {
var hello = $("input[name='category_select']:checked", "#item-upload-form").val();
if(hello == 1){
$("#handy").addClass("selected");
$("#pc").removeClass("selected");
$("#notebook").removeClass("selected");
} else if (hello == 2){
$("#pc").addClass("selected");
$("#handy").removeClass("selected");
$("#notebook").removeClass("selected");
} else if (hello == 3){
$("#notebook").addClass("selected");
$("#pc").removeClass("selected");
$("#handy").removeClass("selected");
}
});
I think #Katana314 had the right answer to the question you're asking. Javascript isn't refreshing the page on each call so the class will stay on the element until you remove it. Might be a little cleaner this way...
$("#item-upload-form input").on("change", function() {
var hello = $("input[name='category_select']:checked", "#item-upload-form").val();
// find any element that has the selected class and remove it
$('.selected').removeClass('selected');
// then add it to which ever element needs it.
if(hello == 1){
$("#handy").addClass("selected");
} else if (hello == 2){
$("#pc").addClass("selected");
} else if (hello == 3){
$("#notebook").addClass("selected");
}
});
Because you're using two selectors and checking hello with the value will only work for those whose both value returns the same value. If both selector value results in different values then your condition never match.
So, it will only match if both values are the same.
Let's keep only calls to addClass(). The code would look like this:
if(hello == 1){
$("#handy").addClass("selected");
} else if (hello == 2){
$("#pc").addClass("selected");
} else if (hello == 3){
$("#notebook").addClass("selected");
}
What happens when you click on radio buttons?
R: Each time it will run only ONE branch. Successive clicks will only addClass to current element, and maintain classes of previous elements.
Why not let jQuery do all of the work for you - this way you can add/remove selections without updating your code:
$("#item-upload-form input").on("change", function (ele) {
$("#item-upload-form input").each(function( ) {
if ($(this).prop('checked')){
$(this).addClass("selected")
} else{
$(this).removeClass("selected") ;
}
});
});
To answer your question, yes, if-else-blocks will stop evaluating if a match is found.
Suggestion 1:
Try using === instead of ==.
=== checks both if the value and type are the same.
== 1 will pass as true for many things, including '1' == 1 and true == 1. I don't know what hello actually is, but you might be getting a false positive.
Suggestion 2:
Here is a revised code suggestion (instead of if-else blocks)
$("#handy").toggleClass("selected", (hello === 1));
$("#pc").toggleClass("selected", (hello === 2));
$("#notebook").toggleClass("selected", (hello === 3));

If select input equals value do this, if it is changed remove those changes

I have a select box called "requestHistoryRequestType". I'm trying to write some jQuery so that when the value of that select box is changed I call a function that adds a class and attribute to a field and appends a span to the field that I pass in as a parameter.
The problem is if a user chooses EXPAPP or EXPDEN but then changes their selection to NA it should remove the added stuff from the previous fields and add the same stuff to a different field. Kinda hard to explain, but ask questions away! I'm kinda new to writing complex jQuery like this.
The function that does the adding classes and such:
function requiredField(requiredField) {
$(requiredField).parent().addClass('has-error');
$(requiredField).attr('data-rule-required', true);
$("label[for='" + requiredField.replace('#', '') + "']").append("<span style='color:#b94a48;' class='has-error has-tooltip' data-placement='right' title='Required Field'>*</span>");
}
The actual on change listener:
//Validations for EXPAPP, EXPDEN, and NA
$("#requestHistoryRequestType").on("change", function() {
if ($("#requestHistoryRequestType").val() === "EXPAPP" || $("#requestHistoryRequestType").val() === "EXPDEN"){
requiredField("#requestHistoryVerbalDateTime");
requiredField("#requestHistoryWrittenDateTime");
} else if ($("#requestHistoryRequestType").val() === "NA") {
requiredField("#requestHistoryComments");
}
});
Thanks Stack!
Create a function that would remove the added stuff from all fields and call it before requiredField() calls:
function removeRequiredFields()
{
var $fields = $("#requestHistoryVerbalDateTime, #requestHistoryWrittenDateTime, #requestHistoryComments");
$fields.parent().removeClass('has-error');
$fields.attr('data-rule-required', false);
$fields.each(function() {
$("label[for='"+$(this).attr('id')+"']").find("[title='Required Field']").remove();
});
}
Or you can pass $fields from the event handler to removeRequiredFields() instead of hardcoding it there, for added flexibility.
I would just have a separate function for when you select a "NA" rather then trying to build that functionality into the same function.
I'll rewrite your event handler to make it a bit cleaner as well (IMO).
//Validations for EXPAPP, EXPDEN, and NA
$("#requestHistoryRequestType").on("change", function() {
var selectedVal = $(this).val();
if (selectedVal === "EXPAPP" || selectedVal === "EXPDEN"){
requiredField("#requestHistoryVerbalDateTime");
requiredField("#requestHistoryWrittenDateTime");
} else if (selectedVal === "NA") {
requiredField("#requestHistoryComments");
}
});
This way you are not hitting the DOM a potential 3 time to test your conditions every time an event is triggered. A minor change but probably a useful one as you get into more complex and larger jQuery selectors.
Edit: If you feel you MUST do it in one function then you can call the function with both elements you want to append
function requiredField(requiredField1, requiredField2) {
if (requiredField2 != null){
$(requiredField1,requiredField1).parent().addClass('has-error');
$(requiredField1,requiredField1).attr('data-rule-required', true);
var requiredLabel = "<span style='color:#b94a48;' class='has-error has-tooltip' data-placement='right' title='Required Field'>*</span>"
$("label[for='" + requiredField1.replace('#', '') + "']").append(requiredLabel);
$("label[for='" + requiredField2.replace('#', '') + "']").append(requiredLabel);
}
else {
//remove multiple element classes and add it to the single one representing the "NA"
}
}
This is based on you only ever having one case where you would be passing a single "requiredField" on a case of a "NA"

How to check if the any of my textbox is empty or not in javascript [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Check if inputs are empty using jQuery
I have form and textboxes, how will I determine if any of these textboxes is empty using javascript if else statement once a form button is clicked.
function checking() {
var textBox = $('input:text').value;
if (textBox == "") {
$("#error").show('slow');
}
}
Thanks in advance!
By using jQuery selectors for selecting the elements, you have a jQuery object and you should use val() method for getting/setting value of input elements.
Also note that :text selector is deprecated and it would be better to trim the text for removing whitespace characters. you can use $.trim utility function.
function checking() {
var textBox = $.trim( $('input[type=text]').val() )
if (textBox == "") {
$("#error").show('slow');
}
}
If you want to use value property you should first convert the jQuery object to a raw DOM object. You can use [index] or get method.
var textBox = $('input[type=text]')[0].value;
If you have multiple inputs you should loop through them.
function checking() {
var empty = 0;
$('input[type=text]').each(function(){
if (this.value == "") {
empty++;
$("#error").show('slow');
}
})
alert(empty + ' empty input(s)')
}
You can not use value with jquery object use val() function, But this will check only the first textbox returned by the selector.
Live Demo
function checking() {
var textBox = $('input:text').val();
if (textBox == "") {
$("#error").show('slow');
}
}
You can attach blur event and do this validation on losing focus from each textbox.
Live Demo
$('input:text').blur(function() {
var textBox = $('input:text').val();
if (textBox == "") {
$("#error").show('slow');
}
});
Validation on submit button click according to discussion with OP
​Live Demo
$('#btnSubmit').click(function() {
$("#error").hide();
$('input:text').each(function(){
if( $(this).val().length == 0)
$("#error").show('slow');
});
});
Try this code:
var textBox = $('input:text').val();
if (textBox==""){
$("#error").show('slow');
}

JS filter textbox input

I hope this isn't a daft question. I expected google to be promising but I failed today.
I have a textbox <input type="text" id="input1" /> that I only want to accept the input /^\d+(\.\d{1,2})?$/. I want to bind something to the keydown event and ignore invalid keys but charCode isn't robust enough. Is there a good jQuery plugin that does this?
The affect I want to achieve is for some one to type 'hello world! 12.345' and want all characters to be ignored except '12.34' and the textbox to read '12.34'. Hope this is clear.
Thanks.
I don't think you need a plugin to do this; you could easily attach an event and write a simple callback to do it yourself like so:
$('#input1').keyup(function()
{
// If this.value hits a match with your regex, replace the current
// value with a sanitized value
});
try this:
$('#input1').change(function(){
if($(this).data('prevText') == undefined){
$(this).data('prevText', '');
}
if(!isNaN($(this).val())){
$(this).val($(this).data('prevText'))
}
else {
//now do your regex to check the number settings
$(this).data('prevText', $(this).val());
}
})
the isNAN function checks to make sure the value is a number
$('#input1').bind('keyup', function() {
var val = $(this).val();
if(!val)
return;
var match = val.match(/^\d+(\.\d{1,2})?$/);
if(!match)
return;
//replace the value of the box, or do whatever you want to do with it
$(this).val(match[0]);
});
jQuery Keyfilter
Usage:
$('#ggg').keyfilter(/[\dA-F]/);
It also supports some pre-made filters that you can assign as a css class.
You should look at jQuery validation. You can define your own checking methods like this here.
$('input1').keyup(function(){
var val = $(this).val().match(/\d+([.]\d{1,2})?/);
val = val == null || val.length == 0 ? "" : val[0];
$(this).val(val);
});
I found the solution.
Cache the last valid input on keydown event
Rollback to last valid input on keyup event if invalid input detected
Thus:
var cache = {};
$(function() {
$("input[regex]").bind("keydown", function() {
var regex = new RegExp($(this).attr("regex"));
if (regex.test($(this).val())) {
cache[$(this).attr("id")] = $(this).val();
}
});
$("input[regex]").bind("keyup", function() {
var regex = new RegExp($(this).attr("regex"));
if (!regex.test($(this).val())) {
$(this).val(cache[$(this).attr("id")]);
}
});
});

Limit Input text box with Jquery

So I need to have an input box in where people only is allowed to enter either the words "Yes" or "No". No other input is allowed. Does anybody out there knows a plugin or any other easy way to that with Jquery? I found a plugin named constraint (http://plugins.jquery.com/project/constrain), that can prevent the user from typing certain characters, but that is not enough, as the plugin can only prevent the user from typing numbers in an alphabetic field, for example. Drop down boxes or other components are not an option.
Thank you for your help.
Why not something like this (link to jsFiddle)? This will only let you type those characters that are contained in an array of allowed values? I suspect there's a better way to check for the existence of values or partial values in the array instead of looping. But this will be triggered by a user's key press, not when the control loses focus...so the UX may be better.
Hope this helps!!
HTML
Enter text: <input type="text" id="data" />
JavaScript Code
var allowedValues = ['yes','no'];
$(document).ready(function() {
$("#data").keyup(function(e) {
var typedValue = $(this).val(),
valLength = typedValue.length;
for(i=0;i<allowedValues.length;i++) {
if(typedValue.toLowerCase()===allowedValues[i].substr(0,valLength)) {
return;
}
}
$("#data").empty().val(typedValue.substr(0, valLength-1));
});
});
Based on clarification in comment, try this:
Try it out: http://jsfiddle.net/fsPgJ/2/
EDIT: Added a keypress event to deal with the user holding down a key.
$('input').blur(function() {
var val = this.value.toLowerCase();
if(val != "yes" && val != "no") {
this.value = '';
alert( "'Yes' or 'No' is required. \n Please try again.");
}
})
.keypress(function() {
var val = this.value.toLowerCase();
if(val != "yes" && val != "no")
this.value = '';
})
.keyup(function() {
var val = this.value.toLowerCase();
if("yes".indexOf(val) != 0 &&
"no".indexOf(val) != 0) {
this.value = this.value.substr(0,this.value.length - 1);
}
});
Original:
If there's some reason you're not using a <select> or :radio or something, then you could have jQuery check the value on a .blur() event.
Try it out: http://jsfiddle.net/fsPgJ/
$('input').blur(function() {
var val = this.value.toLowerCase();
if(val != "yes" && val != "no") {
this.value = '';
alert( "'Yes' or 'No' is required. \n Please try again.");
}
});
This just clears the input if the (case insensitive) value is not "yes" or "no". I also added an alert() to give the user a little feedback as to why the field was cleared. You may want a different feedback approach.

Categories

Resources