1

I have a chunk of HTML code generated with PHP.

HTML looks like this:

<input type="text" id="10"><button onclick="process()">send</button>

<input type="text" id="11"><button onclick="process()">send</button> <!-- and so on until id=N -->

PHP code is like:

<?php while ($row = $result->fetch_assoc()) { ?>
<input type="text" id="<?=$row['id']?>">
<button onclick="process()">send</button>
<br>
<?php } ?>

It is supposed that if a user clicks the SEND button, the value of input tag is passed to process() function.

And here is where I'm getting stuck: I don't know which exactly ID of input should I specify in getElementById within process() fucntion - because I don't know which button is pressed.

Would be greateful for any help.

Ivan
  • 163
  • 1
  • 12

2 Answers2

1

Although it is not prefered way, if you want to stick with inline event handlers, you can do something like this:

function process(elem){
  alert(elem.previousSibling.value);
  
}
<input type="text" id="10"><button onclick="process(this)">send</button>
  <input type="text" id="11"><button onclick="process(this)">send</button>

Note this

Gecko-based browsers insert text nodes into a document to represent whitespace in the source markup. Therefore a node obtained, for example, using Node.firstChild or Node.previousSibling may refer to a whitespace text node rather than the actual element the author intended to get.

previousSibling

The Process
  • 5,913
  • 3
  • 30
  • 41
  • I've got two questions: 1. Why such method is not preferd? 2. What is the "correct" method? – Ivan Mar 23 '16 at 19:02
  • 1
    You will hit problems like code maintainability and empty text nodes like in this example, your process function have to be in global scope etc. Prefered way would be with `.addEventListener('click',process)`, so for example generate the same class name for each input/button pair and attach event listener to the buttons. – The Process Mar 23 '16 at 19:21
  • You can check a simple example : http://jsbin.com/qunite/edit?html,js,console,output – The Process Mar 23 '16 at 19:54
  • And what if I have more than one input elements in a single div with "send" button? How do I get their values – Ivan Mar 27 '16 at 15:11
  • 1
    I've managed to achive my goal with jQuery :) – Ivan Mar 28 '16 at 08:38
1

Like previous answers, you should ideally stay away from binding the events inline. But the solution if you have to do is two, By default an event object is passed to the event handler method if it is not overridden by any one.

such a method will give you enough information about the target element of the event. (The behaviour may vary depending on the browsers so may need to test it thoroughly..)

function EventHandler(e) {
    e = e || window.event; 
    var target = e.target || e.srcElement;
    console.log(target);
}

now you can call the get the id by just doing target.id or you can basically get any attribute value.

Althaf M
  • 498
  • 4
  • 12