0

I have a very simple scenario where I want to have a textbox where you can enter a number, and a button next to it which when pressed will call a javascript method and send it the integer value in the textbox as a parameter.

I am just learning MVC and have been very spoiled by WebForms so forgive me for the silly question, but why doesn't this work?

    Enter Value 1-4<textarea id="param"></textarea>
    <br />
   <button id="btnTest" onclick="WCFJSONp(" + param.value + ")">Test Service</button>

I tried adding a @ sign in front of 'param.value' hoping Razor might see what I'm trying to do, but that didn't work either? And can anyone recommend any links to 'crash courses' in Javascript/HTML for MVC newbs spoiled by WebForms?

2 Answers 2

3

As you state the question this has very little to do with MVC -- this is only javascript. Typically you would use jQuery with javascript when running the MVC platform, in which case something like this would work.

onclick="WCFJSONp($('#param').val());"

vs onclick="WCFJSONp(document.getElementById('param').value)"

When using getElementById you are not using the jQuery library but instead just base JavaScript.

There are advantages and disadvantages to using one over the other.

  • Using base JavaScript is faster, you don't have to load the jQuery library.
  • jQuery can make your scripts more portable (probably not an issue in this case), because it defines an exact interface to the DOM and takes care of any browser specific issues (this is the BIG one for me.)
  • jQuery is easier to use and understand. (some might argue if they are use to base javascript)
  • jQuery has lots of examples of advanced use (also not an issue here).

There are probably more but these are the ones that come right to mind.

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

4 Comments

"Typically you would use jQuery with javascript"... The OP didn't mention jQuery, so if your answer requires jQuery, why not share how to include jQuery source as well?
@Lukas - good point, I edited my answer to explain I meant when using MVC.
can you explain the difference behind the scenes between this and the below answer which uses document.getelementbyid?
@dferraro - sure, see above.
2

This should be:

onclick="WCFJSONp(document.getElementById('param').value)"

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.