简体   繁体   中英

javascript php post undefined

In the following snippet of javascript code, there are times when html element scenario is not present on the php page. So when javascript is called, the value entered in first code line below is "undefined". As the scenario is a numeric input with default value 0, I tried to check if or not posted html element is an integer, so as to restore default value. But its not working. Please guide how to check and restore default value if html element is not present on the page. The remaining code posts the javascript variable into another php file, which updates database and it works fine when html element is actually present on the page. There are different conditions because of which the html element may or may not be present on the php page.

var scenario = $("#scenario"+tournament_id).val();
if(!isNaN(scenario))
{
    scenario = 0;
}

Check if the element exists in the DOM with .length or you can use $("#scenario"+tournament_id).is(':visible') if the element is always going be be visible in the page(if present).

  if($("#scenario"+tournament_id).length==0 || !$("#scenario"+tournament_id).length)
    {
       scenario = 0;
       console.log("no element found");
    }

OR:

if(!$("#scenario"+tournament_id).is(':visible'))
 {
      scenario = 0;
      console.log("no element found");
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM