当前位置: 动力学知识库 > 问答 > 编程问答 >

jquery - Javascript variable values used for URL generation not evaluating as expected

问题描述:

I'm trying to pass a string from a "text" field to an MVC action. The form variable is called query. The Javascript code is:

<input type="text" class="form-control input-lg" placeholder="search..."

name="SearchBar" onkeypress="searchfunction()" />

<script>

function searchfunction()

{

if (event.keyCode == 13) {

var url = '"' + document.getElementById("#SearchBar").value + '"';

window.location = "@Url.Action("~/Home/Search")?query=" + url;

}

}

</script>

The URL generated from this should be domain/Home/Search?query=[contents of textfield] but for some reason it's generating a URL like domain/search.html?SearchBar=[contents of SearchBar] and I get 0x800a138f - JavaScript runtime error: Unable to get property 'value' of undefined or null reference. I am sure those two are related, but .value is what EVERY example I can find recommends using.

Note: I tried using the getElementById both with # and without, same for the name property of the input.

Should I just be passing the string in the onkeypress event? Am I missing something simple? Is this a bug in MVC 3?

网友答案:

try this,

document.getElementById("SearchBar").value

the previous notation comes from jquery.you cannot use them interchangeably.If you prefer the jquery way that would be

$("#Searchbar").val();

and add an id = "Searchbar" to the textfield.

网友答案:

Add the "id" attribute:

<input type="text" class="form-control input-lg" placeholder="search..." 
  name="SearchBar" id="SearchBar" onkeypress="searchfunction()" />

And remove the "#" character from getElementById() method param

网友答案:

You Define getElementsById() So If you select name from any html element you have to ..Use :

getElementsByName() ,Its return Array not a particular element as you want to select.

In your Case ( because you use # inside get function, i assume you have to get ID )

# = ID selector used In JQuery not in pure javascript.

apply ID of your Element :

<input type="text" class="form-control input-lg" placeholder="search..." 
name="SearchBar" id='SearchBar' onkeypress="searchfunction()" />
<script>
 function searchfunction()
 {
  if (event.keyCode == 13) {
    var url = '"' + document.getElementById("SearchBar").value + '"';
    window.location = "@Url.Action("~/Home/Search")?query=" + url;

  }
}
</script>
分享给朋友:
您可能感兴趣的文章:
随机阅读: