Can't change form input value using JavaScript - javascript

I'm trying to implement a simple anti-spam field on my form where the server generates a random string, sends it to the user, and then JavaScript reverses the string before submitting it. If the string doesn't match, the submission is discarded as spam. The issue is that I can't seem to get JavaScript or jQuery to reverse the input value.
$(document.ready(function() {
var reverse = $('#simple').val().split("").reverse().join("");
document.getElementById('simple').setAttribute('value', reverse);
}))
Using
$('#simple').val(reverse);
instead of the setAttribute method also fails.
The input field itself is:
<input type="text" id="simple" name="simple" value="abcde" />
jQuery is being included and I can get the input value to reverse if I type in the same code via the developer tools console, but the page itself doesn't work. Thanks!

You have an error, in the document ready callback, other than that it is fine
$(document).ready(function() {
// ^ need to close the parenthesis here
var reverse = $('#simple').val().split("").reverse().join("");
$('#simple').val(reverse)
//or document.getElementById('simple').setAttribute('value', reverse);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="simple" name="simple" value="abcde" />

$(document.ready(function() {
var reverse = $('#simple').val().split("").reverse().join("");
document.getElementById('simple').value = reverse;
});

var test= document.getElementById("mytext");
test.value = "My default value";

$('#simple').val(reverse); should work if id simple is unique.(no other objects with same id). Also you can use $('input[name=simple]').val(reverse);
Check this jQuery change input text value

Related

Javascript setInterval not working as expected [duplicate]

I had thought these two were the same, but they appear to not be. I've generally been using $obj.attr("value") to work with form fields, but on the page I'm currently building, $obj.attr("value") does not return the text I enter in my field. However, $obj.val() does.
On a different page I've built, both $obj.attr("value") and $obj.val() return the text entered in the form field.
What could account for $obj.attr("value") working as expected in one case but not in another?
What is the proper way to set and retrieve a form field's value using jQuery?
There is a big difference between an objects properties and an objects attributes
See this questions (and its answers) for some of the differences: .prop() vs .attr()
The gist is that .attr(...) is only getting the objects value at the start (when the html is created). val() is getting the object's property value which can change many times.
Since jQuery 1.6, attr() will return the original value of an attribute (the one in the markup itself). You need to use prop() to get the current value:
var currentValue = $obj.prop("value");
However, using val() is not always the same. For instance, the value of <select> elements is actually the value of their selected option. val() takes that into account, but prop() does not. For this reason, val() is preferred.
PS: This is not an answer but just a supplement to the above answers.
Just for the future reference, I have included a good example that might help us to clear our doubt:
Try the following. In this example I shall create a file selector which can be used to select a file and then I shall try to retrieve the name of the file that I selected:
The HTML code is below:
<html>
<body>
<form action="#" method="post">
<input id ="myfile" type="file"/>
</form>
<script type="text/javascript" src="jquery.js"> </script>
<script type="text/javascript" src="code.js"> </script>
</body>
</html>
The code.js file contains the following jQuery code. Try to use both
of the jQuery code snippets one by one and see the output.
jQuery code with attr('value'):
$('#myfile').change(function(){
alert($(this).attr('value'));
$('#mybutton').removeAttr('disabled');
});
jQuery code with val():
$('#myfile').change(function(){
alert($(this).val());
$('#mybutton').removeAttr('disabled');
});
Output:
The output of jQuery code with attr('value') will be 'undefined'.
The output of jQuery code with val() will the file name that you selected.
Explanation:
Now you may understand easily what the top answers wanted to convey. The output of jQuery code with attr('value') will be 'undefined' because initially there was no file selected so the value is undefined. It is better to use val() because it gets the current value.
In order to see why the undefined value is returned try this code in your HTML and you'll see that now the attr.('value') returns 'test' always, because the value is 'test' and previously it was undefined.
<input id ="myfile" type="file" value='test'/>
I hope it was useful to you.
Let's learn from an example.
Let there be a text input field with default value = "Enter your name"
var inp = $("input").attr("value");
var inp = $("input").val();
Both will return "Enter your name"
But suppose you change the default text to "Jose" in your browser.
var inp = $("input").attr("value");
will still give the default text i.e. "Enter your name".
var inp = $("input").val();
But .val() will return "Jose", i.e. the current value.
Hope it helps.
The proper way to set and get the value of a form field is using .val() method.
$('#field').val('test'); // Set
var value = $('#field').val(); // Get
With jQuery 1.6 there is a new method called .prop().
As of jQuery 1.6, the .attr() method returns undefined for attributes
that have not been set. In addition, .attr() should not be used on
plain objects, arrays, the window, or the document. To retrieve and
change DOM properties, use the .prop() method.
In order to get the value of any input field, you should always use $element.val() because jQuery handles to retrieve the correct value based on the browser of the element type.
jQuery('.changer').change(function () {
var addressdata = jQuery('option:selected', this).attr('address');
jQuery("#showadd").text(addressdata);
});
jQuery(".morepost").live("click", function() {
var loadID = jQuery(this).attr('id'); //get the id
alert(loadID);
});
you can also get the value of id using .attr()
this example may be useful:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
</head>
<body>
<input id="test" type="text" />
<button onclick="testF()" >click</button>
<script>
function testF(){
alert($('#test').attr('value'));
alert( $('#test').prop('value'));
alert($('#test').val());
}
</script>
</body>
</html>
in above example, everything works perfectly. but if you change the version of jquery to 1.9.1 or newer in script tag you will see "undefined" in the first alert.
attr('value') doesn't work with jquery version 1.9.1 or newer.
Example more... attr() is various, val() is just one! Prop is boolean are different.
//EXAMPLE 1 - RESULT
$('div').append($('input.idone').attr('value')).append('<br>');
$('div').append($('input[name=nametwo]').attr('family')).append('<br>');
$('div').append($('input#idtwo').attr('name')).append('<br>');
$('div').append($('input[name=nameone]').attr('value'));
$('div').append('<hr>'); //EXAMPLE 2
$('div').append($('input.idone').val()).append('<br>');
$('div').append('<hr>'); //EXAMPLE 3 - MODIFY VAL
$('div').append($('input.idone').val('idonenew')).append('<br>');
$('input.idone').attr('type','initial');
$('div').append('<hr>'); //EXAMPLE 3 - MODIFY VALUE
$('div').append($('input[name=nametwo]').attr('value', 'new-jquery-pro')).append('<br>');
$('input#idtwo').attr('type','initial');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="hidden" class="idone" name="nameone" value="one-test" family="family-number-one">
<input type="hidden" id="idtwo" name="nametwo" value="two-test" family="family-number-two">
<br>
<div></div>
jquery - Get the value in an input text box
<script type="text/javascript">
jQuery(document).ready(function(){
var classValues = jQuery(".cart tr").find("td.product-name").text();
classValues = classValues.replace(/[_\W]+/g, " ")
jQuery('input[name=your-p-name]').val(classValues);
//alert(classValues);
});
</script>
If you get the same value for both property and attribute, but still sees it different on the HTML try this to get the HTML one:
$('#inputID').context.defaultValue;
In attr('value') you're specifically saying you're looking for the value of an attribute named vaule. It is preferable to use val() as this is jQuery's out of the box feature for extracting the value out of form elements.
I have always used .val() and to be honest I didnt even know you could get the value using .attr("value"). I set the value of a form field using .val() as well ex. $('#myfield').val('New Value');

How to validate in JS if an HTML5 input pattern has been matched?

I have something like this:
<input type="text" id="number_field" pattern="[-+]?[0-9]*[.,]?[0-9]+" />
I can target custom css if the pattern is not matched using the :invalid selector.
I want to disable a submit button that makes an XHR if all the validation isn't met.
<button class="AdamBrown" onclick="saveAdamBrown(12)">Save</button>
How can I assess whether the pattern is met in Javascript?
var input = document.getElementById("number_field")
input.checkValidity()
checkValidity will simply return true or false. If you want to know why it fails validation, you can explore the input.validity object.
You can use the HTML5 constraint validation API (https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation
). You can check if you input pattern check is valid by checking the value of validity.patternMismatch of that element. Please see the snippet below with the example:
var numberField = document.getElementById("number_field");
var button = document.getElementsByClassName('AdamBrown')[0];
numberField.addEventListener("input", function (event) {
button.disabled = numberField.validity.patternMismatch;
});
<input type="text" id="number_field" pattern="[-+]?[0-9]*[.,]?[0-9]+" />
<button class="AdamBrown" onclick="saveAdamBrown(12)">Save</button>

Setting input value to attribute value in JQuery

I have a number of <input /> boxes which I want to start off having a value of something like "Enter your name...".
When you focus them, the value becomes empty and you can type away. When you blur them, if nothing has been entered, then it goes back to "Enter your name...".
I thought of having something like this:
<input id="name" _startValue="Enter your name..." />
Then, something like this:
$(document).ready($("input").val($(this).attr(_startValue)));
This initially should set the value to _startValue but it does nothing. Replacing the line with:
$(document).ready($("input").val("hello"));
does work, however, so the problem must be with the $(this) or the attr().
First of all, how do I get this to work. Secondly, if I am trying to do this in a really retarded way, what is a good way to get this functionality?
I believe its better to use a placeholder like:
<input id="name" placeholder="Enter your name..." />
There are already libraries for this, and if you are already using jquery you should use them.
https://github.com/mathiasbynens/jquery-placeholder
just add the attribute "placeholder" and invoque the function:
<input placeholder="my placeholder">
<script type="text/javascript">
$("document").ready(function(){
$("input").placeholder();
});
</script>
Note that you only need to add the plugin if you need old browser support (in IE specially), otherwise, the attribute is enough.
Also, consider that if you code this, it will take you errors like submitting the default value of the form. What jquery plugins do generally is to make a <span> or whatever and place it on top of the input when the input is empty, and hide it when the input is not empty.
// v---you're not passing a function
$(document).ready($("input").val($(this).attr(_startValue)));
// `this` isn't magic-------^---- It doesn't just mean what you want
Should be more like this:
$(document).ready(function() {
$("input").val(function() {
return $(this).attr("_startValue");
});
});
A common way to mimic placeholders is to put the placeholder text in the element's value, then check the value on focus like:
if (this.value == this.defaultValue) this.value = '';
and then on blur:
if (this.value == '') this.value = this.defaultValue;
Please don't use placeholders instead of labels or onscreen help (e.g. format for dates). If a browser doesn't support the placeholder attribute, it's probably best not to emulate them if using it for the default value is an issue.
After all, placeholders are a "nice to have", they should not be fundamental to using the form correctly.

jquery escape square brackets to select element

Consider a input element
<input id="meta[152][value]" type="text" />
Here the input field is dynamically generated. I need to select that field. So I used,
alert($('#meta[152][value]').val());
But this seems to be invalid. After searching I found, that the "square brackets" need to be escaped like #meta\\[152\\]\\[value\\]
So how to do that ?
I currently use this code,
var id = "#meta[152][value]" // (I get this value by another method) I need the escaping to be done here. So that i can use as
/** I need the value of id to be escaped using regex,replace or any other method
to get #meta\[152\]\[value\]
and not manually **/
alert($(id).val());
Your suggestions will be helpful !
The following should work:
alert($('#meta\[152\]\[value\]').val());
or
var id = "#meta\[152\]\[value\]";
alert($(id).val());
Working Example
Conversion Function:
function ConvertValue(id)
{
var test = id.replace(/[[]/g,'\\\\[');
return "#" + test.replace(/]/g,'\\\\]');
}
Conversion Example
If you feel more comfortable without escaping you also use the attributes selector and search for the element with that id like this: $("[id='meta[152][value]']")
The simplest way is just to use the regular getElementById, which requires no escaping:
document.getElementById("meta[152][value]").value;
this shoudl work for you, you almost had it:
$(document).ready(function() {
var id = "#meta\\[152\\]\\[value\\]";
alert($(id).val());
});
Um, just put the escaped value right in your string.
var id = "#meta\\[152\\]\\[value\\]";
See it working here
You can use the _.escapeRegExp method from the Lodash library.
console.log($('#' + _.escapeRegExp('meta[152][value]')).val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
<input id="meta[152][value]" type="text" value='Test' />

Javascript for mobile HTML form

I am having some problems with Javascript :(
This is an HTML form for a mobile webpage. To save space I put the names of the text fields inside the boxes. The name disappears when you focus on the box, but I am not able to make it reappear if the user didn't write anything.
Here is the Script (in head tag):
<script type="text/javascript"> resetDefault();{if (this.value.length==0); this.value="default";} </script>
Here is the HTML code:
<input onfocus="this.value=''" onblur="resetDefault()" name="nom" type="text" value="Nom complet" default="Nom complet"/><br><input onfocus="this.value=''" onblur="resetDefault()"name="courriel" type="text" value="Courriel" default="Courriel"/><br>
I keep getting a "resetDefault is not defined" error. I don't know if default is an accepted attribute for input, but I can't set it to "value" because value becomes 0 once someone has focused on the text field, right?
There are several problems with your javascript code. First, it is not syntactically correct. You should first change this code
resetDefault();
{if (this.value.length==0);
this.value="default";}
so that it has valid syntax, like this:
function resetDefault(){
if(this.value.length == 0){
this.value = "default";
}
}
The second problem is that this refers to the global object, instead of the DOM node you want. You need to pass in a value so it knows which input to change.
Change the onblur javascript so that it passes in a parameter to the function:
onblur="resetDefault(this);"
and change the function so it accepts a parameter:
function resetDefault(that){
if (that.value.length == 0){
that.value="default";
}
}
The third problem is that "default" will just change the value of the input box to the string, "default". I doubt that is what you want. Make the value match the default attribute you gave the input:
that.value = that.getAttribute("default");
Try it out on JSFiddle
The semicolon after resetDefault() in the script in the head needs to be removed - now it's a function call of a function that's not defined.
<script type="text/javascript">function resetDefault() { if (this.value.length==0) this.value="default";} </script>
You need to define the resetDefault() function like so:
function resetDefault() {
// Function stuff here
}

Categories

Resources