Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript indexOf

Tags:

javascript

I'm not well clued up with javascript so I'm having a problem getting the following script to work. I need to check if a name entered is also contained within a message.

<input type="hidden" id="Message" value="<%= rsDetail.Fields("Message") %>">
<input type="hidden" id="FirstName" value="<%= rsDetail.Fields("FirstName")%>">

<script type="text/javascript">
<!--
function NameCheck(){
var FirstName=document.getElementByID('FirstName');
var CardMessage=document.getElementByID('Message');
var aPosition = CardMessage.indexOf('FirstName');

if (aPosition == -1)
alert("Name Not In Message.");
}
-->
</script>

<a href="NextPage.asp" onClick="NameCheck();">Proceed</a>
like image 336
Darren Cook Avatar asked Oct 19 '11 13:10

Darren Cook


People also ask

What is indexOf JavaScript?

JavaScript String indexOf() The indexOf() method returns the position of the first occurrence of a value in a string. The indexOf() method returns -1 if the value is not found. The indexOf() method is case sensitive.

What indexOf () will do?

indexOf() The indexOf() method, given one argument: a substring to search for, searches the entire calling string, and returns the index of the first occurrence of the specified substring.

Can we use indexOf in array?

indexOf() The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

What can I use instead of indexOf in JavaScript?

indexOf(v) instead, where ~ is the JavaScript bitwise NOT operator.


1 Answers

It seems like you are trying to get the value of the input FirstName. getElementById() only returns the node itself. Instead access its value:

var FirstName = document.getElementById('FirstName').value;
var CardMessage = document.getElementById('Message').value;

// Then use the variable `FirstName` instead of the quoted string
var aPosition = CardMessage.indexOf(FirstName);

// Best practice would be to use === for strict type comarison here...
if (aPosition === -1)
  alert("Name Not In Message.");
}

Also, note that you've misspelled getElementById, with a capital D at the end where it should be lowercase.

like image 177
Michael Berkowski Avatar answered Oct 21 '22 17:10

Michael Berkowski