JQuery-Form not getting my input value the first time
I have a form that has 2 inputs, very simple.
<form class="cform">
<input type="text" name="cname" class="cname" id="cname" autofocus placeholder="Firstname Lastname">
<div class="floatl regards"><input type="submit" value="Submit" class="submit" id="submit"></div>
</form>
My JQuery:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$("#submit").click(function()
{
var CName = $("#cname").val();
console.log(CName);
});
</script>
My problem is when I add a word to the textbox and click the submit button, it doesn't show anything in the console, unless I type the same word and submit it! And it works in the second click. I notice that it doesn't work, it doesn't add those words to the url, and I have to write exactly the same word a second time and hit submit if I want it to work! How can I fix this error? which part of my code is wrong !?
source to share
Clicking on your button will submit the form using the GET method to the current page, causing you to see the word in the link after clicking, all you need to do is to prevent the button type from changing to button
instead of from submit
, which will prevent the page from refreshing:
<input type="text" name="cname" class="cname" id="cname" autofocus placeholder="Firstname Lastname">
Or you could add e.preventDefault()
or return false;
instead of js code:
$("#submit").click(function(e){
e.preventDefault(); //That will prevent the click from submitting the form
var CName = $("#cname").val();
console.log(CName);
return false; //Also prevent the click from submitting the form
});
Hope it helps.
$("#submit").click(function(){
var CName = $("#cname").val();
console.log(CName);
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="cform">
<input type="text" name="cname" class="cname" id="cname" autofocus placeholder="Firstname Lastname">
<div class="floatl regards"><input type="button" value="Submit" class="submit" id="submit">
</div>
</form>
source to share
When you click the submit button, the page will reload and your jQuery definition will not be recognized. To prevent using the html button instead of the input input button.
Or you can use e.preventDefault();
inside your function call to prevent the form from being submitted. To use this, you must pass the event as a parameter using the function (e) {}
source to share