This is perhaps very basic jquery syntax, but I am not very familiar with it. I want to make a jquery ajax call only when an html input with a specific id exists on the page. How do I do this?
You can check if an element with the id exists on page, using length on the selector.If yes, perform your request
if($("#yourId").length>0){
//Your request
$.post( "ajax/test.html", function( data ) {
});
}
</body
-tag)or wait for the document ready DOM-event.$( document ).ready(function() {
if ( $('#jepp').length ) { // 0 validates falsy and != 0 truthy
$('#jepp').val('do your stuff eg ajax')
}
});
// or a little bit more advanced
$(function() { // document ready
if ( document.getElementById('jepp') ) { // vanilla JavaScript but still straight forward
$('#jepp').val( $('#jepp').val() + ' | a bit more advanced')
}
})
<input id="jepp" value="" style="width:100%">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</div>
<input name="foo" id="data">
<script type="javascript">
...
var elementSize = $('#data').size();
if(size > 0){
$.ajax({
...
});
// Page contains id
}else {
//Page doesn't contains id
}
...
</script>
You can do like that.
$('#element-id').size()
or $('#element-id').length
is size of id element. Id value must be 1 and unique. you check size, and make ajax call