jQuery: passing argument to a function not working - javascript

I have problem with passing an argument to my simple function in jQuery:
When function is attached directly to the element everything is OK.
$companyNameInputs.bind('blur keyup',function(){
if ($(this).hasClass('required')) {
if (this.value == ''){
$(this).addClass('inputError');
}else {
$(this).removeClass('inputError');
}
}
});
but when I want to declare this simple check as an different function it doesn't work:
this is my function:
var standardCheck = function($param){
$param.addClass('inputError');
if ($param.hasClass('required')) {
if ($.trim($param).value == ''){
$param.addClass('inputError');
}else {
$param.removeClass('inputError');
}
}
};
and this is how I call it:
$companyNameInputs.bind('blur keyup',function(){
standardCheck($(this));
});
variable declaration:
var $companyNameInputs = $("#companyName")
and the HTML:
<div>
<p>
<input class="text_input" type="text" id="companyName" name="companyName" value="" />
</p>
</div>
please help.

Since param is a jQuery container, you have to call .val() and trim the output of that:
if ($.trim($param.val()) == ''){
or get the corresponding DOM element and its value property.
if ($.trim($param[0].value) == ''){

Related

JQuery .each function not working

I am trying to understand why the following doesn't work:
function SetMaxLength() {
var form = $("body").find("form");
form.each(function () {
var elements = $(this).find("input");
elements.each(function() {
var attr = $(this).attr('data-val-maxlength-max');
if (typeof attr !== typeof undefined && attr !== false) {
$(this).attr('maxlength', attr.value);
}
});
});
}
<form action="/go/somewhere" autocomplete="off" class="form-one" method="post" role="form" novalidate="novalidate">
<input data-val-maxlength="Invalid Email" data-val-maxlength-max="254" type="text" value="">
</form>
when I step through it, it finds 1 form but then on the each part it just skips it, steps over it.
Basically all it is suppose to do it when it sees data-val-maxlength-max attribute, it is suppose to take its value and inject maxlength attribute in the element.
JsFiddle: https://jsfiddle.net/j04vue8r/3/
Since you already have jQuery included in your page, it's better to rewrite your code and make it more "jQuery style".
Here we go:
$('[data-val-maxlength-max]').each(function(){
$(this).attr('maxlength', $(this).data('val-maxlength-max'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/go/somewhere" autocomplete="off" class="form-one" method="post" role="form" novalidate="novalidate">
<input data-val-maxlength="Invalid Email" data-val-maxlength-max="254" type="text" value="">
</form>
I've tried your code and it not step over the each function. The problem is the attr() function that doesn't set the maxlenght attribute because you have a mistake in the code: attr is just the value of data-val-maxlength-max and so you have to write something like this:
$(this).attr('maxlength', attr);
This does what you need:
$(function() {
$("form input").each(function() {
var attr = $(this).attr('data-val-maxlength-max');
if (typeof attr !== undefined && attr !== false) {
$(this).attr('maxlength', attr);
}
});
});
There are two problems with above code.
1. Function SetMaxLength is not called
2. variable attr already contains value. So you don't need to do attr.value
Below code works
function SetMaxLength() {
var form = $("body").find("form");
form.each(function () {
var elements = $(this).find("input");
elements.each(function() {
var attr = $(this).attr('data-val-maxlength-max');
if (typeof attr !== typeof undefined && attr !== false) {
$(this).attr('maxlength', attr);
}
});
});
}
SetMaxLength()
Try this
window.onload = function () {
SetMaxLength();
}
function SetMaxLength() {
var form = $("body").find("form");
form.each(function () {
var elements = $(this).find("input");
elements.each(function() {
var attr = $(this).attr('data-val-maxlength-max');
console.log(attr);
if (typeof attr !== typeof undefined && attr !== false) {
$(this).attr('maxlength', attr);
}
});
});
}
All I did was remove attr.value in your if statement. Works fine for me. You don't need the value, since you already grabbed it in the variable : ). I'd encourage you not to use generic terms like "form" and "elements" and "attr". They might cause issues.
By the way, in the future you may wish to use console.log. It helped me figure out the issue here. I did console.log(attr) right after the var attrline to see what we were getting. In Chrome you can view the console by hitting ctrl + shift + J. Since I saw that it was 254, I knew we didn't need to get a new value : ).

jQuery get input val() from $("input") array

I have a function that returns whether or not every text input in a form has a value.
When I first made the function it looked like this:
function checkInput(inputId) {
check = 0; //should be 0 if all inputs are filled out
for (var i=0; i < arguments.length; i++) { // get all of the arguments (input ids) to check
var iVal = $("#"+arguments[i]).val();
if(iVal !== '' && iVal !== null) {
$("#"+arguments[i]).removeClass('input-error');
}
else {
$("#"+arguments[i]).addClass('input-error');
$("#"+arguments[i]).focus(function(){
$("input").removeClass('input-error');
$("#"+arguments[i]).off('focus');
});
check++;
}
}
if(check > 0) {
return false; // at least one input doesn't have a value
}
else {
return true; // all inputs have values
}
}
This worked fine, but when I called the function I would have to include (as an arstrong textgument) the id of every input I wanted to be checked: checkInput('input1','input2','input3').
Now I am trying to have my function check every input on the page without having to include every input id.
This is what I have so far:
function checkInput() {
var inputs = $("input");
check = 0;
for (var i=0; i < inputs.size(); i++) {
var iVal = inputs[i].val();
if(iVal !== '' && iVal !== null) {
inputs[i].removeClass('input-error');
}
else {
inputs[i].addClass('input-error');
inputs[i].focus(function(){
$("input").removeClass('input-error');
inputs[i].off('focus');
});
check++;
}
}
if(check > 0) {
return false;
}
else {
return true;
}
}
When I call the function it returns this error:
Uncaught TypeError: inputs[i].val is not a function
What am I doing wrong?
When you do inputs[i], this returns an html element, so it is no longer a jquery object. This is why it no longer has that function.
Try wrapping it with $() like $(inputs[i]) to get the jquery object, and then call .val() like:
$(inputs[i]).val()
If you are going to use this in your for loop, just set it as a variable:
var $my_input = $(inputs[i])
Then continue to use it within the loop with your other methods:
$my_input.val()
$my_input.addClass()
etc..
if you use jquery .each() function, you can do it a little cleaner:
$(document).ready(function() {
$('.submit').on('click', function() {
$('input').each(function() {
console.log('what up');
if($(this).val().length < 1 ) {
$(this).addClass('input-error');
}
else {
$(this).removeClass('input-error');
}
});
});
});
.input-error {
background-color: pink;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" /><br/>
<input type="text" /><br/>
<input type="text" /><br/>
<input type="text" /><br/>
<input type="text" /><br/>
<input type="text" /><br/>
<input type="text" /><br/>
<input type="text" /><br/>
<input type="text" /><br/>
<input type="text" /><br/>
<br/>
SUBMIT
This is actually a very simple fix. You need to wrap you jquery objects within the jquery constructor $()
Such as for inputs[i].val() to $(inputs[i]).val();
Here is the full working example:
http://jsbin.com/sipotenamo/1/edit?html,js,output
Hope that helps!
This is exactly one of the things the .eq() method is for. Rather than using inputs[i], use the following:
// Reduce the set of matched elements to the one at the specified index.
inputs.eq(i)
Given a jQuery object that represents a set of DOM elements, the .eq() method constructs a new jQuery object from one element within that set. The supplied index identifies the position of this element in the set.
in this case, I would make use of the jQuery.each() function for looping through the form elements. This will be the modified code
function checkInput() {
var $inputs = $("input"),
check = 0;
$inputs.each(function () {
val = $.trim($(this).val());
if (val) {
$(this).removeClass('input-error');
}
else {
$(this).addClass('input-error');
$(this).focus(function () {
$("input").removeClass('input-error');
$(this).off('focus');
});
check++;
}
});
return check == 0;
}

Keep getting value of text input

For the following code:
<script>
var text = document.form.text.value;
function test() {
if(text == "" || text == null){
alert('No value');
return false
}else{
alert(text);
}
};
</script>
<form>
<input type="text" name="text" id="text_one"/>
</form><a id="button" onClick="test();">Enter</a><br />
<div id="title_box"></div>
Why does it keep alerting 'No Value' even when something has been written? And what would have to be done so that every time a new value is entered, the function gets that new value instead of the old one?
function test() {
text = document.forms[0].text.value;
if(text == "" || text == null){
alert('No value');
return false;
}else{
alert(text);
}
};
Put text var inside function. Also, notice using of document.forms[0], or give form name/id, as suggested.
Try this code...there are a couple of changes:
<script>
var text = document.forms.myForm.text.value.trim();
function test() {
if(text == "" || !text){
alert('No value');
return false;
} else {
alert(text);
}
}
</script>
<form id="myForm">
<input type="text" name="text" id="text_one"/>
</form>
In summary:
Missing semicolon in your function after return false
Give your form an id
A null value for text is efficiently detected using trim() AND ! (here as !text)
Because you either have to move the script block after the form closing tag </form>, or you have to put the variable code inside the script block in the window.onload
window.onload = function(){
var text = document.form.text.value;
}
function test() {
if(text == "" || text == null){
alert('No value');
return false
}else{
alert(text);
}
};
or
<form>
<input type="text" name="text" id="text_one"/>
</form>
<script>
var text = document.form.text.value;
function test() {
if(text == "" || text == null){
alert('No value');
return false
}else{
alert(text);
}
};
</script>
<a id="button" onClick="test();">Enter</a><br />
<div id="title_box"></div>
Explanation: The function is correct, but the text variable is initialized before creating the DOM, so it will contain a value of undefined. That's why you have to initialize it after that the DOM is loaded by putting the script code after the form, or by initialize it in the window.onload

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>

Using JQuery to get the default value of a textarea, clearing onfocus and reinstating value on empty

I have some JQuery that isn't working and I need a little help. I a few forms on my website, and they all have a textarea with the class ".form-textarea". What I'm trying to do is use JQuery to get the default value of the textarea, clear the value on focus and reinstate the original value if the the textarea is empty. I realise that an ID would probably be better but I need a generic function to affect all of the textareas with this particular class.
$(document).ready(function()
{
var def = $(".form-textarea")
$(".form-textarea").focus(function(srcc)
{
if ($(this).val() == def)
{
$(this).removeClass("defaultTextActive");
$(this).val("");
}
});
$(".form-textarea").blur(function()
{
if ($(this).val() == "")
{
$(this).addClass("defaultTextActive");
$(this).val(def);
}
});
$(".defaultText").blur();
});
This is an old method I used for the exact same purpose. I believe this is what you're looking for (uses Textareas) : Live demo
This uses the jQuery data API. I've also added an extra class so you can markup your text nicely (disabled_text). This is a general purpose method so all you need to do is add the suggest class to your textarea/input and the script will do the rest
<textarea class='suggest'>Some default value</textarea>
<textarea class='suggest'>Some default value2</textarea>
<textarea class='suggest'>Some default value3</textarea>
<input type='text' value ='me too' class='suggest'>
$('.suggest').each(function() {
$this = $(this);
if ($this.val() != '') {
return;
}
$this.data('defaultval', $this.val());
$this.addClass('disabled_text').focus(function() {
if ($this.val() == $this.data('defaultval')) {
$this.val('');
}
$this.removeClass('disabled_text');
}).blur(function() {
var oldVal = ($this.data('defaultval')) ? $this.data('defaultval') : '';
if ($this.val() == '' && oldVal != '') {
$this.addClass('disabled_text').val(oldVal);
}
})
});
Here, give this a whirl and see if it does the trick.
<script>
$(document).ready(function(){
$default = "defaultText";
$(".form-textarea").focus(function(){
if( $(this).val() == $default ){
$(this).removeClass("defaultTextActive");
$(this).val("");
}
});
$(".form-textarea").blur(function(){
if( $(this).val() == "" ){
$(this).addClass("defaultTextActive");
$(this).val($default);
}
});
});
</script>
<input class="form-textarea" type="text" value="defaultText" />
<input class="form-textarea" type="text" value="defaultText" />
I've just tried to remove the value "srcc" from the focus function and it works fine

Categories