1

I've a script:

<form id="myform">
    <input type="text" value="" id="input1">
    <input type="text" value="" id="input2">
    <input type="submit" value="submit">
</form>
<img id="image" src="http://mydomain.com/empty.gif" />
<script>
$(document).ready(function () {
    $("#myform").submit(function (ev) {
        ev.preventDefault();
        var val1 = $("#input1").val();
        var val1 = $("#input2").val();
        $("#image").attr("src", "http://mydomain.com/image?val1="+val1+"&val2="+val2);
    });
});
</script>

How would it look like if written in JavaScript?

5
  • 3
    I'm being somewhat pedantic, but...jQuery is Javascript, what you have written is perfectly valid Javascript it just happens to depend on jQuery. What you're asking for is a non-jQuery dependant version. Commented May 11, 2011 at 12:40
  • Please use proper indenting when submiting your code. Commented May 11, 2011 at 12:40
  • 2
    I think you made a mistake: you're declaring val1 twice. Commented May 11, 2011 at 12:42
  • 1
    It is Javascript (using some functions brought into scope by the jQuery library). jQuery is not a language. Commented May 11, 2011 at 12:49
  • Can't he just add "plain" to the title? Commented May 11, 2011 at 13:44

1 Answer 1

3
<img id="image" src="http://mydomain.com/empty.gif" />
<script>
window.onload = function() { // Not all browsers support DOMContentLoaded
  document.getElementById("myform").onsubmit = function() {
     var val1 = document.getElementById("input1").value;
     var val2 = document.getElementById("input2").value;
     document.getElementById("image").src="http://mydomain.com/image?val1="+val1+"&val2="+val2;
     return false;
   };
};
</script>

If you NAME the fields you can use

window.onload = function() {
  document.getElementById("myform").onsubmit = function() {
     document.getElementById("image").src="http://mydomain.com/image?val1="+this.input1.value+"&val2="+this.input2.value;
     return false;
   };
};

You MAY want to escape the two values

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

9 Comments

You miss return false;. Moreover, you're waiting for onload, not DOMContentLoaded, etc. ;-)
@Marcel: I already fixed the return false and DCL is not supported by a lot of browsers
I know, but I just wanted to nit-pick a bit about this code not being exactly equivalent to the OP's (and to make him aware of the uses of frameworks).
But in IE8, jQuery would convert DOMContentLoaded to onload, no?
+1 for the de-jQueryizing. -1 for not fixing the OP's misconception.
|

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.