September 30, 201015 yr I have 3 forms which each have 1 input fields in them. When the user starts to type in the input field it calls a javascript function. At the moment I have the following code but how can I detect which input field is being typed in? For example if it is "input1" or "input3"? Then based on that I'm going to change the variable called "url" in the function. Thanks for any help. function showResult(str) { var url = "update_location.php?search_term=" + escape(str); request.open("GET", url, true); request.onreadystatechange = updateLocation; request.send(null); }
October 1, 201015 yr It depends how you're assigning the functionality to those input boxes and when you're checking if the user has typed anything. If you have cerated a custom event for key typing, you'll need the event argument. If you have assigned a event to something like the change event, something like this: document.getElementById('myInput1').onchange = function() {...} you will need the this keyword. If you are using a timeout to check if the value has changed then it may be a little more complicated. Do you have an online example?
October 2, 201015 yr Author Thanks. I don't have an online example but I have copied the code below. The three input fields use the onkeyup event handler. <form action="<?php echo ( $_SERVER['PHP_SELF'] ); ?>" method="post"> <input name="archive_search" type="text" id="archive_search" autocomplete="off" onkeyup="showResult(this.value)" /> <input type="submit" name="archive_submit" value="Search archive" /> </form> <form action="<?php echo ( $_SERVER['PHP_SELF'] ); ?>" method="post"> <input name="author_search" type="text" id="author_search" autocomplete="off" onkeyup="showResult(this.value)" /> <input type="submit" name="author_submit" value="Search archive" /> </form> <form action="<?php echo ( $_SERVER['PHP_SELF'] ); ?>" method="post"> <input name="company_search" type="text" id="company_search" autocomplete="off" onkeyup="showResult(this.value)" /> <input type="submit" name="company_submit" value="Search archive" /> </form>
October 2, 201015 yr Author Yeah so basically when the function "showResult" is called I just want the first line of that function to detect which input field called the function.
October 2, 201015 yr Oh, that's pretty straight-forward. Firstly, change the id attributes of your inputs so they're all unique. Next, instead of passing "this.value" to your showResult function, just pass "this". Then just modify your showResult function slightly: function showResult(elem) { var str = elem.value, url = ''; if (elem.id == "search_site") { url = "update_location.php?search_term=" + escape(str); } else if (elem.id == "search_archive") { //... continue like this... } //... continue with your function } And that should do it
Create an account or sign in to comment