0

I have a C# MVC4 application in which I am writing a JQuery function to grab some values, post to an ActionResult and then refresh a partial view. All functionality is working except for setting a new var equal to the value of a variable within one of my div elements.

The pre-existing variable is called myName and is located in a div with an id of NameDiv.

Ive tried these four versions of code and each results in: Reference Error myName is not defined.

    var origname = myName;    
    var origname = myName.value();
    var origname = myName.val();
    var origname = $('#NameDiv').valueOf(myName);

When running the application and inspecting element, I see that myName is populating with the correct value.

4
  • What do you mean by "the value of a variable within one of my div elements"? Commented Apr 14, 2013 at 5:07
  • myName - variable, html element, ...? Commented Apr 14, 2013 at 5:10
  • @Ian I mean that I have an html textbox with the name "myName" and the value entered by the user is what I am trying to pass and store in the var named "origname" shown above. Commented Apr 14, 2013 at 5:10
  • @HendPro12 I just added an answer. Does that work? Commented Apr 14, 2013 at 5:11

1 Answer 1

2

Use:

var origname = $('#NameDiv').find('input[name="myName"]').first().val();
// console.log(origname);

This will find the element on the page with the id of "NameDiv". Then it gets the input elements on the page with the name of "myName". Then it gets the first one found. It will then get the value of it (by using .val()), and store that value in the variable origname.

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

4 Comments

I havent tried yet but I dont believe it will because I have two textboxes in the div
@HendPro12 Do both textboxes have the same id "NameDiv"?
neither textbox has an id at this moment each just has a "name." However, both are located in a div with the id "NameDiv." Is there no way to do what Im desiring without giving each individual textbox an id?
@HendPro12 It would definitely be more helpful if you provided more code/HTML. I just updated my answer with hopefully a better solution. Sorry I misunderstood at first

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.