javascript - onClick event not working - JS -


i writing simple search function return similar results database based on user selected, though when testing onclick function not working have checked code similar , should work, searched before asking question though no solution me, sample of code..`

<form> <fieldset>     <legend>search form..</legend>     <input type="text" id="itemid" name="itemname" placeholder="enter item name.." />     <select id="locselect">     <option id="loc1" value="mountain"> mountain </option>     </select>     </br>     <input type="button" id="searchid" name="searchname" value="search" onclick="runsearch();" />   </fieldset> </form>  <div id="searchresult"></div>  <script type="text/javascript">  function runsearch() {     var item = $("#itemid").val();      var location = document.getelementbyid("#locselect");     var selectedloc = location.options[location.selectedindex].text;      if(item == '')      {        alert("item field blank please specify item");     }      else { $.post("lsr.php", {         postitem = item,         postlocation = selectedloc },          function(data)         {             $("#searchresult").html(data);         });     } } </script> 

it should take user selected , send php page compare database, wrote similar code login/registration page , worked, i'm not sure why 1 doesn't, thing different select, options.. understand doing wrong. thank in advance.

you've got catch 22 here, if put function above form, #itemid doesn't exist in dom yet. if put function below form, function runsearch doesn't exist yet.

why not use:

$(document).ready(function(){     $(document).on("click", "#searchid", function(e){         console.log("clicked!"); //watch console this, delete line once know works.         runsearch();     }); }); 

also, have few things wrong code (including colons/equal signs mentioned in answer). i've cleaned bit.

this wrong: document.getelementbyid("#locselect");

if you're using document.getelementbyid, don't need #. that's jquery id selector. but, you're using jquery, embrace it! equivalent of document.getelementbyid in jquery $("#idofelement").

all of location.options[location.selectedindex].text can shortened this: location.val(), use $ prefix jquery objects it's obvious they're jquery objects, renamed variable $location.

here's working fiddle:

http://jsfiddle.net/seankendle/b9udzjlp/


Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -