I have the following code:
<form action="" method="get" onsubmit="doRequest($('word').value); $('word').value=''; return false;">
<input type="text" name="word" id="word" value="" />
<input type="submit" name="submit" value="Send" />
</form>
doRequest() function:
function doRequest(request)
{
$.ajax(url, {
type: 'get',
data: { 'msg' : request }
});
}
The problem is, if I change the word value manually like value="111", I can see the value is being posted to PHP. However, when I want it to post whatever I write into textarea, it posts nothing, so the problem lies in the onSubmit area.
Can anybody help me about this?
You are missing the # in your jQuery selectors.
onsubmit="doRequest($('#word').value); $('#word').value=''; return false;"
I would also remove the inline JavaScript and replace it with a function in the submit handler instead. Also using jQuery .val() instead of .value.
$(document).ready(function() {
$('form').submit(function() {
doRequest($('#word').val());
$('#word').val('');
return false;
});
});
The correct way to access the value via jQuery is val() - not by setting a property.
$(...).val("set the value");
var get_the_value = $(...).val();
Also, your current selectors are looking for <word> elements which you hopefully don't have. Use #word as the selectors to search by ID.
Related
I'm working on an ASP.net web application.
I have a form with a submit button. The code for the submit button looks like <input type='submit' value='submit request' onclick='btnClick();'>.
I want to write something like the following:
function btnClick() {
if (!validData())
cancelFormSubmission();
}
How do I do this?
You are better off doing...
<form onsubmit="return isValidForm()" />
If isValidForm() returns false, then your form doesn't submit.
You should also probably move your event handler from inline.
document.getElementById('my-form').onsubmit = function() {
return isValidForm();
};
Change your input to this:
<input type='submit' value='submit request' onclick='return btnClick();'>
And return false in your function
function btnClick() {
if (!validData())
return false;
}
You need to change
onclick='btnClick();'
to
onclick='return btnClick();'
and
cancelFormSubmission();
to
return false;
That said, I'd try to avoid the intrinsic event attributes in favour of unobtrusive JS with a library (such as YUI or jQuery) that has a good event handling API and tie into the event that really matters (i.e. the form's submit event instead of the button's click event).
Sometimes onsubmit wouldn't work with asp.net.
I solved it with very easy way.
if we have such a form
<form method="post" name="setting-form" >
<input type="text" id="UserName" name="UserName" value=""
placeholder="user name" >
<input type="password" id="Password" name="password" value="" placeholder="password" >
<div id="remember" class="checkbox">
<label>remember me</label>
<asp:CheckBox ID="RememberMe" runat="server" />
</div>
<input type="submit" value="login" id="login-btn"/>
</form>
You can now catch get that event before the form postback and stop it from postback and do all the ajax you want using this jquery.
$(document).ready(function () {
$("#login-btn").click(function (event) {
event.preventDefault();
alert("do what ever you want");
});
});
you should change the type from submit to button:
<input type='button' value='submit request'>
instead of
<input type='submit' value='submit request'>
you then get the name of your button in javascript and associate whatever action you want to it
var btn = document.forms["frm_name"].elements["btn_name"];
btn.onclick = function(){...};
worked for me
hope it helps.
This is a very old thread but it is sure to be noticed. Hence the note that the solutions offered are no longer up to date and that modern Javascript is much better.
<script>
document.getElementById(id of the form).addEventListener(
"submit",
function(event)
{
if(validData() === false)
{
event.preventDefault();
}
},
false
);
The form receives an event handler that monitors the submit. If the there called function validData (not shown here) returns a FALSE, calling the method PreventDefault, which suppresses the submit of the form and the browser returns to the input. Otherwise the form will be sent as usual.
P.S. This also works with the attribute onsubmit. Then the anonymus function function(event){...} must in the attribute onsubmit of the form. This is not really modern and you can only work with one event handler for submit. But you don't have to create an extra javascript. In addition, it can be specified directly in the source code as an attribute of the form and there is no need to wait until the form is integrated in the DOM.
You need to return false;:
<input type='submit' value='submit request' onclick='return btnClick();' />
function btnClick() {
return validData();
}
With JQuery is even more simple: works in Asp.Net MVC and Asp.Core
<script>
$('#btnSubmit').on('click', function () {
if (ValidData) {
return true; //submit the form
}
else {
return false; //cancel the submit
}
});
</script>
Why not change the submit button to a regular button, and on the click event, submit your form if it passes your validation tests?
e.g
<input type='button' value='submit request' onclick='btnClick();'>
function btnClick() {
if (validData())
document.myform.submit();
}
You need onSubmit. Not onClick otherwise someone can just press enter and it will bypass your validation. As for canceling. you need to return false. Here's the code:
<form onSubmit="return btnClick()">
<input type='submit' value='submit request'>
function btnClick() {
if (!validData()) return false;
}
Edit onSubmit belongs in the form tag.
It's simple, just return false;
The below code goes within the onclick of the submit button using jquery..
if(conditionsNotmet)
{
return false;
}
use onclick='return btnClick();'
and
function btnClick() {
return validData();
}
function btnClick() {
return validData();
}
<input type='button' onclick='buttonClick()' />
<script>
function buttonClick(){
//Validate Here
document.getElementsByTagName('form')[0].submit();
}
</script>
I need to set a form input value to -1 when submitted if nothing is entered.
So far I have this function, but it doesn’t change the value to -1.
<form action="validate.php"
method="post" onsubmit="return validate()" >
<input type="text" name="CategoryID" size="3" maxlength="3" onkeyup="checkCategoryID(this)"/>
function validate()
{
var catID;
catID = document.getElementsByName("CategoryID");
if (catID.value == "")
catID.value = -1;
return true;
}
There are a number of issues with your code. First, JavaScript code should either be included in a separate javascript file or embedded inside script tags.
Second, you'll want to use return false instead of return true.
Also, the default behavior of a form, is for it to be submitted. You might want to pass in a parameter event and use the event.preventDefault method.
Also, getElementsByName returns a collection not a single element. You need to pass in an index like so
getElementsByName("categoryID")[0];
The form tag requires the closing tag </form>.
catID.value == "" is searching for an empty string. You can use a boolean instead. It's equivalent to !catID.value
Here is my temporary solution.
<form action="validate.php"
method="post" onsubmit="validate()" >
<input type="text" name="CategoryID" size="3" maxlength="3" onkeyup="checkCategoryID(this)"/>
</form>
<script>
var catID = document.getElementsByName("CategoryID")[0];
function validate() {
if (!catID.value) {
catID.value = -1;
return false;
}
}
</script>
How to call function xxx when input type text id="username" change value ?
first, when you fill data into
<input type="text" name="thingy" onkeypress="updateInput(this.value)" onkeyup="updateInput(this.value)" />
Then data in
<input type="text" name="thingy" onkeypress="updateInput(this.value)" onkeyup="updateInput(this.value)" />
will change value.
OK, when input name="thingy" change i want to call function xxx , i try this code but not work.
How can i do that ?
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
function updateInput(ish){
document.getElementById("username").value = ish;
}
</script>
<form id="main_fid">
input1 : <input type="text" name="thingy" onkeypress="updateInput(this.value)" onkeyup="updateInput(this.value)" />
<span id="mySpan"></span>
<input type="submit" value="OK"/>
</form>
<script>
function xxx() {
$.ajax
(
{
url: 'other.php',
type: 'POST',
data: $('#username_send_value_fid').serialize(),
cache: false,
success: function (data) {
$('#mySpan').show();
$('#mySpan').html(data);
}
}
)
}
</script>
<br>
<form id="username_send_value_fid">
input2 : <input type="text" name="username" id="username" onchange="xxx()" readonly/>
</form>
I think calling xxx() on "onchange" event or inside updateInput(ish) will give the same effect.
Try
function updateInput(ish){
document.getElementById("username").value = ish;
xxx();
}
$("#username").on( "change", handler )
or in short form
$("#username").change( handler )
And get rid of the inline onchange attribute. You will also need to wrap the code in a ready function:
$(document).ready(function(){
$("#username").change( handler )
});
http://api.jquery.com/change/
Added after reading the question a bit more carefully:
If you want to link your input name="thingy" to username you can do something like this:
$('input[name="thingy"]').change(function(){
$("#username").val( $(this).val() ).trigger('change');
});
This will update the value of username and then trigger a change event as if the user had typed in the input.
However if what you are trying to accomplish is something like validating the uniqueness of an input the is no reason to jump though so many hoops - just call your ajax handler straight from the username change event.
I have an input text box that is in a form, and I'm trying to retrieve the value and multiply it to the parameter.
It doesn't run and I'm not sure if there's a syntax error or if my retrieval of textbox value is incorrect.
<script>
function product(parameter1) {
a=parseInt(document.myForm.myTextBox.value);
return parameter1*a;
};
</script>
HTML:
<form name='myForm'>
Insert your number: <input id='myTextBox' value=''><br>
</form>
<input type='button' value='CLICK HERE' onclick='product()'>
You miss an argument in the onclick trigger, it should be ="product(10)", where 10 is your paremeter1 argument.
I believe you would have to have a name on the input tag to access it the way you do, so an easier and probably faster way to access your input would be document.getElementById('myTextBox')
It is better to execute your product() function on form submit, rather than on button click event, since some users might want to just hit enter in the text field instead of the button, but then you would have to move it within the form boundaries and make it be type="submit"
MODIFIED CODE:
js:
<script>
function product(parameter1) {
a = parseInt(document.getElementById('myTextBox').value, 10);
var result = parameter1*a;
// alert(result);
return result;
};
</script>
html:
<form name='myForm' onsubmit="product(10); return false;">
Insert your number: <input id='myTextBox' value=''><br>
<input type='submit' value='CLICK HERE'>
</form>
You were calling method without argument. If you only want to retrieve value, below is the code. I dont know how ur going to use it
Insert your number:
<input type='button' value='CLICK HERE' onclick='product()'>
<script>
function product()
{
parameter1=10;
a=parseInt(document.myForm.myTextBox.value);
return parameter1*a;
}
</script>
I've got a form that has multiple submit buttons. One for changing data in a database, one for adding, and one for deleting. It looks like this:
<form action="addform.php" method="post" id="addform" onSubmit="return validate(this)">
<select name="listings" id="listings" size="1" onChange="javascript:updateForm()">
<!-- Here I have a php code that produces the listing menu based on a database query-->
</select>
<br />
Price: <input type="text" name="price" id="price" value="0"/><br />
Remarks: <textarea name="remarks" wrap="soft" id="remarks"></textarea><br />
<input type="submit" value="Update Database Listing" name="upbtn" id="upbtn" disabled="disabled"/>
<input type="submit" value="Delete Database Listing" name="delbtn" id="delbtn" disabled="disabled"/>
<br />
<input type="submit" value="Add Listing to Database" name="dbbtn" id="dbbtn"/>
<input type="button" value="Update Craigslist Output" name="clbtn" id="clbtn" onClick="javascript:updatePreview();"/>
</form>
There are actually more elements in the form, but that doesn't matter. What I want to know is, for my validation method, how can I check which submit button has been clicked?
I want it to do the following:
function validate(form){
if (the 'add new listing' or 'update listing' button was clicked'){
var valid = "Are you sure the following information is correct?" + '\\n';
valid += "\\nPrice: $";
valid += form.price.value;
valid += "\\nRemarks: ";
valid += form.remarks.value;
return confirm(valid);}
else {
return confirm("are you sure you want to delete that listing");
}
}
I assume there must be some way to do this relatively easily?
Why don't you set a global variable specifying which button was last clicked? Then you can check this variable in your validate method. Something like:
var clicked;
$("#upbtn").click(function() {clicked = 'update'});
// $("#delbtn").click(function() {clicked = 'delete'});
// ...
function validate(form) {
switch(clicked) {
case 'update':
break;
// more cases here ...
}
}
You can, for example, attach a click event to every submit button that will save a pointer to it in a variable or mark it with a specific attribute / class (it that case you will have to remove that marker from all other submit buttons in the event handler) and then in the submit callback you will know which one was clicked
I think it's easier to just use a click event on each button and handle it individually.
$(function() {
$('input[name=someName]').click(someFunc);
});
function someFunc() {
// Your validation code here
// return false if you want to stop the form submission
}
You could have a hidden field on a form and set the value of that field on clicking the button and then pick it up in your validation routine. You can use jquery to achieve this, let me know if you require an example.
You can use ajax submission with jQuery, you can try something like this:
$('form#addform input[type="submit"]').on('click',function(e){
e.preventDefault();
var current = $(this); //You got here the current clicked button
var form = current.parents('form');
$.ajax({
url:form.attr('action'),
type:form.attr('method'),
data:form.serialize(),
success:function(resp){
//Do crazy stuff here
}
});
});