1

everyone,i am a beginner about js,so i have a Question,code:

var formDate=$("#formStudentInfo").serializeArray();
    var inputArray=[];

     for (var i=0;i<formDate.length;i++) {

        var element=$('#form_'+formDate[i]['name']);
        inputArray.push(element);
        console.log(inputArray)
        inputArray[i].on('click',function(){
            console.log(inputArray[0]['name']);
        })
     }

i have a form name is #formStudentInfo,there are two input in this form,input name is "form_name"and"form_userName",How do I get the input name,when i click input? thanks everyone

3
  • Make a fiddle please Commented May 20, 2016 at 9:13
  • i remember as3 do it is "buttons[i].addEventListener(MouseEvent.CLICK, clickHandler);" ,how to do in js? Commented May 20, 2016 at 9:14
  • Use 'onclick' event w3schools.com/jsref/event_onclick.asp in html <element onclick="myScript"> Commented May 20, 2016 at 9:16

1 Answer 1

1

You shouldn't use the looping counter variable inside the asynchronous callback handler.

Value of i will not be same when the element is clicked. since by that time it will always be equal to formDate.length since when the element is clicked this loop has already run.

Replace

inputArray[i].on('click',function(){
    console.log(inputArray[0]['name']);
})

with

element.on('click',function(){
   console.log($(this).attr('name')); //using the reference to current element using $(this)
})

or simply

element.click(function(){ //directly using the click method rather than delegation
   console.log($(this).attr('name')); //using the reference to current element using $(this)
})
Sign up to request clarification or add additional context in comments.

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.