I have a json array of values that is dynamically populated and returned via an ajax call. This json data can contain any number of objects. For example, my ajax call returned an array of gems ['ruby', 'emerald', 'topaz'].
On my html page I have a text input somewhere on the page where a user can add a new gem. When the user adds a gem (via a button click), I want to see if it already exists in my json array. So if user enters 'diamond' then ultimately a check box should get checked.
My code:
function AddGem(data){ //data is the dynamically populated data from my ajax call
var gem = $("#Gem").val(); // this the text input value of the textbox where a user can enter a gem. I am checking the json array values against this value
$("#Button").click(function() { //user clicks a button to add a gem to the input textbox
$.each(data, function (item) {
if(item === 'gem')
{
$("#Oldform").prop("checked", false); // leave checkbox unchecked
} else
{
$("#Oldform").prop("checked", true); //check check box
}
});
});
}
How can I execute the search of my json array? Do I need to create an empty array first ie. data = [];? Thanks,
I think you wanted to use gem
variable instead of 'gem'
string.
Something like:
$("#Button").click(function() {
$.each(data, function (item) {
$("#Oldform").prop("checked", item === gem);
});
});
But consider using indexOf
:
$("#Button").click(function() {
$("#Oldform").prop("checked", data.indexOf(gem)>-1);
});
To search the json data, I used a for loop with a break statement. When an element in the array (data) is matched with the text input, the for loop is exits.
var jsonData = null;
function AddGem(data){
jsonData = data;
$("#Button").click(function(){
for (var i = 0; i < data.length; i++){
if (data[i] == $("#Gem").val())
{
//leave check box unchecked
break;
}
else{
//check check box
}
}
});
}