I'm working on a simple if/else jquery statement and I ran into some trouble with the variable. What I need it to do is to check if the var is true. In my case I want it to check if the has 'dont push' in it. If it's true, the html must change to 'lol'. If not, it will give a simple alert. Can anybody give me some guidance here?
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="user-scalable=no, width=device-width" />
<title>Untitled Document</title>
<link href="mobile.css" rel="stylesheet" type="text/css" media="only screen and (max-width: 480px)" />
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#nietklikken').click(function() {
var n = $(this).html('dont push');
if (n == "$(this).html('dont push')"){
$(this).html('lol')
} else {
alert('lolz');
}
});
});
</script>
</head>
<body>
<button type="button" id="nietklikken">dont push</button>
</body>
</html>
$(this).html()
will get
the innerhtml value and $(this).html(arg)
will set
the innerhtml value. The correct usage will be below.
$('#nietklikken').click(function() {
if ($(this).html().indexOf('dont push') > -1){
$(this).html('lol')
} else {
alert('lolz');
}
});
You should read up more in jquery docs .
Update : It will now check if the innerhtml contains 'dont push'.
You could use the ' indexOf ' operator that should tell you if a string contains another string. Try -
if ($(this).html().indexOf('dont push') != -1){
$(this).html('lol')
} else {
alert('lolz');
}
In general you could use a function like this
function HasSubstring(string,substring){
if(string.indexOf(substring)>-1)
return true;
return false;
}
A working javascript code to check if string contains the specific word/substring:
var inputString = "this is my sentence";
var findme = "my";
if ( inputString.indexOf(findme) > -1 ) {
out.print( "found it" );
} else {
out.print( "not found" );
}
You can get the HTML content of an element by calling the html()
method with no arguments like so:
var innerHtml = $(someElement).html();
You can then check for the presence of a string by using indexOf
like so:
var position = "Find the string".indexOf("the");
// position = 5
If the given string isn't present, indexOf
will return -1.
var position = "Find the string".indexOf("notFound");
// position = -1
You can then use this in an if
statement like so
if($(someElement).html().indexOf("dont push") >-1)
{
// Required action here
}
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.