You can see the code below, you can enter any value and then append it to the div. I want to add a code that make sure the value appear on the div first and make sure it is exist and then run the code. Because I am using .ajax to make a search function, so I want to make sure the value is exist in the div and the run the .ajax. So, I am thinking about if input_length is greater than current length, but I don't know if that correct or not. because input_length actually is the current length,right? Help, appreciate.
$( "#input" ).keydown(function( event ) { if ( event.which == 13 ) { event.preventDefault(); //put input value into div var value=$('#input').val(); $('#word').append(" " + value); } var input_length=$('#word').text.().length(); //I want to code if one word add and exist, then run my .ajax code. });
.test {display:inline-block;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="word" id="word">dog</div> <input type="text" id="input"/>
This question doesn't make a lot of sense to me, but you can check to see if the word in question exists like this:
// With jQuery
var newWord = $('#input').val();
var wordContainer = $('#word');
if (wordContainer.text().indexOf(newWord) < 0) {
wordContainer.append(' ' + newWord);
}
// Or with plain JavaScript
var newWord = document.getElementById('input').value;
var wordContainer = document.getElementById('word');
if (wordContainer.innerText.indexOf(word) < 0) {
wordContainer.appendChild(document.createTextNode(' ' + word));
}
Both append
and appendChild
synchronously add the word, so you don't need to check after using them. It's definitely there. ;)
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.