1

I have a code javascript of a action form:

<form name="myform" onsubmit="return OnSubmitForm();" method="post">
<input type="text" value="" id="type" />
<input type="submit" value="submit" />
</form>

And javascript:

function OnSubmitForm() {
    var type = document.getElementById('type').value;
    if(type == '1') {
        document.myform.action = "index.php?type=1";
    }
    if(type == '2') {
        document.myform.action = "index.php?type=2";
    }
    return false;
}

How to convert this javascript to jquery, please this ideas?

1
  • 2
    jQuery is Javascript. What do want? .prop('action', 'index.php?type=1') maybe? Commented Dec 29, 2011 at 4:54

2 Answers 2

4
$("form[name='myform']").submit(function() {
    this.action = "index.php?type=" + this.type.value;
    return false;
});
  • form[name='myForm'] selects a form with the name myForm.
  • Calling .submit(function () { ... }) binds an event handler for the submit event.
  • Inside the function, this refers to the form.

Example: http://jsfiddle.net/4SZrH/ (check out the form action in Firebug or similar).

Sign up to request clarification or add additional context in comments.

1 Comment

I noticed that myform was the name and not id thanks to your answer, so +1
1

First note that this function always returns false, so your form will never submit. But to answer your question, you could use jQuery's submit event

$("form[name='myform']").submit(function(){
    var type = this.type.value;
    if (type === '1' || type === '2')
        this.action = "index.php?type=" + type;

    return false;
});

Or more simply:

$("#myForm").submit(OnSubmitForm);

Also note that, for dom level 0 event handlers, you don't want the return statement inline. In the future just do

<form name="myform" onsubmit="OnSubmitForm();" 

And let OnSubmitForm return true or false

Finally, note that in JavaScript, functions starting with a capital letter by convention denote a constructor. Consider renaming this function to onSubmitForm

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.