when i try to get the text value from the input text, the value returned is "undefined". This function return: "username: undefined" and my input text have a value.
this.loadForm = function() {
$("#response-container").load("formLogin.php", function() {
$("#formLogin").submit(function(event) {
var user = $("#username").val();
alert("username: "+user);
event.preventDefault();
});
});
}; //END loadForm FUNCTION
formLogin.php
<form id="formLogin" method="get" action="20.html">
USERNAME:
<br>
<input type="text" name="username" />
<br> PASSWORD:
<br>
<input type="password" name="password" />
<br>
<br>
<input type="submit" value="Log in" name="login" id="btnInputLogin" onsubmit="return false" />
</form>
Check Your Selector
You need to use an id attribute if you are using the $('#id') syntax in jQuery as the # indicates that you are explicitly targeting an element with the id attribute that follows the # character:
<input type="text" id='username' name="username" />
If you want to reference something by a name, you would need to use an attribute equals selector to explicitly target the name attribute :
var user = $('[name="username"]').val();
There is no input with #username. Either add that id attribute or use
$('input[name="username"]')
Replace:
<input type="text" name="username" />
To
<input type="text" name="username" id="username"/>
Looks like your jquery here: $("#username").val(); is trying to get an id that doesn't exist.
You could add an id to the password input <input id="password"> which should work.
Or you can get it with the current name $('[name="password"]').val()
Related
I have a form which asks user to give some input values. For some initial inputs i am doing custom validation using javascript. At the end of form one field is validated using "html required attribute". But when user clicks on submit button, input box which have required attribute shows message first instead of giving chance to previous ones i.e. not following order of error display. Below i added code and image , instead of showing that name is empty it directly jumps to location input box. This just confuses the end user. Why this problem occurs and how to resolve it?
<html>
<head>
<script>
function validate(){
var name = document.forms['something']['name'].value.replace(/ /g,"");
if(name.length<6){
document.getElementById('message').innerHTML="Enter correct name";
return false;
}
}
</script>
</head>
<body>
<form name="something" action="somewhere" method="post" onsubmit="return validate()">
<div id="message"></div>
Enter Name : <input type="text" name="name" /> <br/> <br/>
Enter Location : <input type="text" name="location" required="required" /> <br/> <br/><br/> <br/>
<input type="submit" name="submit" />
</form>
</body>
</html>
This is probably just the HTML5 form validation triggered because of the required attribute in the location input.
So one option is to also set the required attribute on the name. And or disable the HTML5 validation with a novalidate attribute. See here for more information: https://stackoverflow.com/a/3094185/2008111
Update
So the simpler way is to add the required attribute also on the name. Just in case someone submits the form before he/she entered anything. Cause HTML5 validation will be triggered before anything else. The other way around this is to remove the required attribute everywhere. So something like this. Now the javascript validation will be triggered as soon as the name input looses focus say onblur.
var nameElement = document.forms['something']['name'];
nameElement.onblur = function(){
var messageElement = document.getElementById('message');
var string = nameElement.value.replace(/ /g,"");
if(string.length<6){
messageElement.innerHTML="Enter correct name";
} else {
messageElement.innerHTML="";
}
};
<form name="something" action="somewhere" method="post">
<div id="message"></div>
Enter Name : <input type="text" name="name" required="required" /> <br/> <br/>
Enter Location : <input type="text" name="location" required="required" /> <br/> <br/><br/> <br/>
<input type="submit" name="submit" />
</form>
Now the above works fine I guess. But imagine you might need that function on multiple places which is kind of the same except of the element to observe and the error message. Of course there can be more like where to display the message etc. This is just to give you an idea how you could set up for more scenarios using the same function:
var nameElement = document.forms['something']['name'];
nameElement.onblur = function(){
validate(nameElement, "Enter correct name");
};
function validate(element, errorMessage) {
var messageElement = document.getElementById('message');
var string = element.value.replace(/ /g,"");
if(string.length < 6){
messageElement.innerHTML= errorMessage;
} else {
messageElement.innerHTML="";
}
}
<form name="something" action="somewhere" method="post">
<div id="message"></div>
Enter Name : <input type="text" name="name" required="required" /> <br/> <br/>
Enter Location : <input type="text" name="location" required="required" /> <br/> <br/><br/> <br/>
<input type="submit" name="submit" />
</form>
I want to check that user eneters valid name in english using latin alphabet and valid name in russian using cyrillic alphabet.
I'm having following edit.jsp form:
<body>
<h1>${faculty.name}</h1>
<div class="form">
<form id="edit_faculty" action="controller" method="POST">
<input type="hidden" name="command" value="editFaculty" />
<div class="field">
<label for="name_ru"> Name (ru)</label> <input type="text"
name="name_ru" value="${requestScope.name_ru}" required />
</div>
<div class="field">
<label for="name_eng"> Name (eng)</label> <input type="text"
name="name_eng" value="${requestScope.name_eng}" required />
</div>
</form>
</div>
<script src="/Project/script/faculty-validation.js"></script>
</body>
And the faculty-validation.js:
document.getElementById('name_ru').onkeypress = function(e) {
return (/[А-Яа-я]/.test(String.fromCharCode(e.charCode)));
}
document.getElementById('name_eng').onkeypress = function(e) {
return (/[a-zA-Z]/.test(String.fromCharCode(e.charCode)));
}
I follow this links, but main answer's were to check the place in the page where programer put script src tag.
Error TypeError: document.getElementById(...) is null when add text innerHTML using javascript?
TypeError: document.getElementById() is null
I'm debugging this in Mozilla and getting TypeError. I also tried to modify js code with no success to:
window.onload = function() {
document.getElementById('name_ru').onkeypress = function(e) {
return (/[А-Яа-я]/.test(String.fromCharCode(e.charCode)));
}
}
document.getElementById works with the id attribute, not name. I don't see id attributes for your input tags.
Replace:
<input type="text" name="name_ru" value="${requestScope.name_ru}" required />
with:
<input type="text" name="name_ru" id="name_ru" value="${requestScope.name_ru}" required />
and:
<input type="text" name="name_eng" value="${requestScope.name_eng}" required />
with:
<input type="text" name="name_eng" id="name_eng" value="${requestScope.name_eng}" required />
I have a simple form like this:
<form method="post" id="login">
Username: <input type="text" value="" name="usr" />
Password: <input type="password" value="" name="pw"/>
<input type="submit" id="log" name="log" value="Login" style="width:250px;"/><br/>
</form>
But i keep getting cannot read property for my javascript with this line:
var usr = login.usr.value;
var pw = login.pw.value;
What is the reason i get this error ?
Try to give your form a name and change your code like below :
<form method="post" id="login" name="login">
Username: <input type="text" value="" name="usr" />
Password: <input type="password" value="" name="pw"/>
<input type="submit" id="log" name="log" value="Login" style="width:250px;"/><br/>
</form>
and the in your javascript :
var usr = document.login.usr.value;
You can check here (jsfiddle link).
<input type="text" value="" name="usr" /> does not magically become the variable login.usr, you need to define the value based on the DOM.
var usr = document.login.usr.value;
Try using getElementsByName:
The getElementsByName() method accesses all elements with the specified name.
var usr = document.getElementsByName('usr')[0].value;
var pw = document.getElementsByName('pw')[0].value;
http://jsfiddle.net/L3RvL/
Method 1:
<form method="post" id="login">
Username: <input type="text" value="" name="usr" />
var form = document.getElementById("login"); //DOM access
var usr = form.elements["usr"]; // Forms access
Method 2 - not valid xhtml:
<form method="post" name="login">
Username: <input type="text" value="" name="usr" />
var form = document.login; // Forms access
var usr = form.elements["usr"]; // Forms access
Method 3:
<form method="post">
Username: <input type="text" value="" name="usr" />
var usr = document.getElementsByName("usr")[0]; // first field on page named this
Method 4: - preferred these days since ID MUST be unique - less useful if there are more forms with usr on the page that needs same validation
<form method="post">
Username: <input type="text" value="" id="usr" name="usr" />
var usr = document.getElementById("usr");
Works in every browser:
document.forms["login"].elements["usr"].value;
document.forms["login"].elements["pw"].value;
I am using a jquery template to dynamically generate multiple elements on the same page. Each element looks like this
<div id ="DynamicValueAssignedHere">
<div class="something">Hello world</div>
<div class="formdiv">
<form name="inpForm">
<input type="text" name="FirstName" />
<input type="submit" value="Submit" />
</form>
</div>
</div>
I would like to use Jquery to process the form on submit. I would also like to revert the form values to their previous values if something should go wrong. My question is
How can I get the value of input box using Jquery? For example, I can get the value of the div with class "something" by doing
var something = $(#DynamicValueAssignedHere).children(".something").html();
In a similar fashion, I want to be able to retrieve the value of the textbox. Right now, I tried
var text = $(#DynamicValueAssignedHere).children(".formdiv").findnext('input[name="FirstName"]').val();
but it doesn't seem to be working
You have to use value attribute to get its value
<input type="text" name="FirstName" value="First Name" />
try -
var text = $('#DynamicValueAssignedHere').find('input[name="FirstName"]').val();
It can be much simpler than what you are doing.
HTML:
<input id="myField" type="text" name="email"/>
JavaScript:
// getting the value
var email = $("#myField").val();
// setting the value
$("#myField").val( "new value here" );
An alternative approach, without searching for the field html:
var $form = $('#' + DynamicValueAssignedHere).find('form');
var formData = $form.serializeArray();
var myFieldName = 'FirstName';
var myFieldFilter = function (field) {
return field.name == myFieldName;
}
var value = formData.filter(myFieldFilter)[0].value;
$("form").submit(function(event) {
var firstfield_value = event.currentTarget[0].value;
var secondfield_value = event.currentTarget[1].value;
alert(firstfield_value);
alert(secondfield_value);
event.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" >
<input type="text" name="field1" value="value1">
<input type="text" name="field2" value="value2">
</form>
if you know the id of the inputs you only need to use this:
var value = $("#inputID").val();
var textValue = $("input[type=text]").val()
this will get all values of all text boxes. You can use methods like children, firstchild, etc to hone in. Like by form
$('form[name=form1] input[type=text]')
Easier to use IDs for targeting elements but if it's purely dynamic you can get all input values then loop through then with JS.
You can try these lines:
$("#DynamicValueAssignedHere .formdiv form").contents().find("input[name='FirstName']").prevObject[1].value
You can get any input field value by
$('input[fieldAttribute=value]').val()
here is an example
displayValue = () => {
// you can get the value by name attribute like this
console.log('value of firstname : ' + $('input[name=firstName]').val());
// if there is the id as lastname
console.log('value of lastname by id : ' + $('#lastName').val());
// get value of carType from placeholder
console.log('value of carType from placeholder ' + $('input[placeholder=carType]').val());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="formdiv">
<form name="inpForm">
<input type="text" name="firstName" placeholder='first name'/>
<input type="text" name="lastName" id='lastName' placeholder='last name'/>
<input type="text" placeholder="carType" />
<input type="button" value="display value" onclick='displayValue()'/>
</form>
</div>
I have a webpage with jquery generating dynamic html input boxes.
Something like this appears on the page.
<input type="text" id="numbers[]" ></input>
<input type="text" id="numbers[]" ></input>
<input type="text" id="numbers[]" ></input>
<input type="text" id="numbers[]" ></input>
These text-boxes all use the same autocompleter, is it possible in jQuery to point my autocompleter at all of these?
First of all id should be unique in the whole document so your code is not correct.
What you probably mean is
<input type="text" name="numbers[]" ></input>
<input type="text" name="numbers[]" ></input>
<input type="text" name="numbers[]" ></input>
<input type="text" name="numbers[]" ></input>
To enable autocomplete on those boxes just use the selector that will match them all
var data = "foo bar baz";
$('input[name^=numbers]').autocomplete(data);
You could add a div that wraps input and that is never changed, then upon creation of new input store its id in jquery internal cache, just like this:
var $input = '<input name=somename[] type="text"/>';
$('#mywrap').append($input);
$input.data('id', 'some id');
Then on you can access autocompleter in the following way:
$('#mywrap input').live('click', function() {
var id = $(this).data('id');
// and now do anything with the new id you have!
});