I'm trying to add a value of checked for specific elements.
function renderList() {
$.getJSON("/search", function(response) {
$.each(response, function(index, value) {
$('ul').append($('<li>')
.append(value.task)
.append('<input type="checkbox"/>')
.append('<span>x</span>'))
})
});
}
I would like to add a conditional statement for the checkbox value of "checked"
When I add .attr('checked', true), it is added to the li and not the checkbox.
You can do something like this:
function renderList() {
$.getJSON("/search", function(response) {
$.each(response, function(index, value) {
var checkedString = '';
if( value == 'something'){
checkedString = 'checked="checked"';
}
$('ul').append($('<li>')
.append(value.task)
.append('<input type="checkbox" ' + checkedString + '/>')
.append('<span>x</span>'))
})
});
you can try
$.each(response, function(index, value) {
var valueChecked = (value.checked)? ' checked ': '';
$('ul').append($('<li>' + value.task +
'<input type="checkbox" '+ valueChecked +' />' +
'</li>')
valueChecked get ' checked ' value if value.checked (the property choosed by you) is true;
there's no need to write .append('li') .... .append('
Hope this help you!
Related
I am trying to get the todo titles from jsonplaceholder.typicode.com JSON. I have three buttons and each botton has and id, that id is related to the json todo. When you click on a botton you see the title of that json todo.
Button 1 = jsonplaceholder.typicode.com/todos/1 Button 2 =
jsonplaceholder.typicode.com/todos/2 etc..
$('button').click(function (event) {
var id = event.target.id;
console.log(id);
$.ajax({
url: "https://jsonplaceholder.typicode.com/todos/" + id,
type: "GET"
}).done(function (data) {
$('#result').append('<div class="todo"></div>');
$.each(data, function (key, value) {
if (key == "title") {
$('.todo').append('<p>' + key + ': ' + value + '</p>');
}
});
}).fail(function (event) {
alert(event.status);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="1">A</button>
<button id="2">B</button>
<button id="3">C</button>
<div id="result">
</div>
The problem is that titles repeat each time I click on a button. Why this occurs?
Why? Because you append another <div class="todo"></div> each time button is clicked and then append the content to every one that exists
You can isolate the new <div class="todo"> and only append the new content to that
var $todo = '<div class="todo"></div>'
$('#result').append($todo);
$.each(data, function(key, value) {
if (key == "title") {
$todo.append('<p>' + key + ': ' + value + '</p>');
}
});
Or empty the $('#result') before you add the new content if you don't want to see the first set by changing:
$('#result').append('<div class="todo"></div>');
To
$('#result').html('<div class="todo"></div>');
On each ajax done callback you first create a new todo div:
$('#result').append('<div class="todo"></div>');`
and after that, you add the result to all elements with a todo class:
$('.todo').append('<p>' + key + ': ' + value + '</p>');
I'd suggest removing the first line and changing the second to $('#result')
need an help on a jquery script.
I have a select that trigger from Ajax a list of options available. Once user click this option if a variable got 1 a HTML div is added, if i change to another value HTML disappear. This script work as well first time: i click a option and div appear, when i click other option disappear but this cycle is completed if i it another time select option this stop working...
This is the code:
<script type="text/javascript">
$(document).ready(function() {
request_url = 'opzioni-select';
$.ajax({
url: request_url,
success: function(data){
$('#id_opzione').html("");
$.each(data, function(i, item){
var id = item.id;
var parent_id = item.parent;
var nome_opzione = item.nome_opzione;
var nome_parent = item.nome_parent;
$('#id_opzione').append('<option data-opzione="'+ item.nome_parent +'" data-parent="'+ item.parent +'" id="' + item.nome_opzione +'" value="' + item.id + '">' + item.nome_opzione +'</option>');
});
$(document).on('change', '.opzione', function(){
var parent = $('#id_opzione').find(':selected').data('parent');
var nome_parent = $('#id_opzione').find(':selected').data('opzione');
if(parent != null) {
$('#parent-div').append('<label for="parent-div" class=" control-label col-md-4 text-left">'+ nome_parent +'</label><div class="col-md-6"><input type="text" name="valore_parent" class="form-control"></div><div class="col-md-2"></div>');
} else {
$('#parent-div').hide('fast');
}
});
}
});
});
</script>
I tried to change div id in class and switched to "on('change" instead of call directly the #div with .change( but nothing.
Few problems - you're appending a bunch of options - then delegating for a class that i cant see being created.. Id recommend moving the delegated event to the document ready function. . and using the id of the select - and selecting the option after that using this.
<script type="text/javascript">
$(document).ready(function() {
request_url = 'opzioni-select';
$.ajax({
url: request_url,
success: function(data){
$('#id_opzione').html("");
$.each(data, function(i, item){
var id = item.id;
var parent_id = item.parent;
var nome_opzione = item.nome_opzione;
var nome_parent = item.nome_parent;
$('#id_opzione').append('<option data-opzione="'+ item.nome_parent +'" data-parent="'+ item.parent +'" id="' + item.nome_opzione +'" value="' + item.id + '">' + item.nome_opzione +'</option>');
});
});
$('#id_opzione').on('change', function(){
alert('Changed');
var parent = $('#id_opzione').find(':selected').data('parent');
var nome_parent = $('#id_opzione').find(':selected').data('opzione');
if(parent != null) {
$('#parent-div').append('<label for="parent-div" class=" control-label col-md-4 text-left">'+ nome_parent +'</label><div class="col-md-6"><input type="text" name="valore_parent" class="form-control"></div><div class="col-md-2"></div>');
} else {
$('#parent-div').hide('fast');
}
});
}
});
</script>
so below is my snippet. What I want is to create a select dropdown option base from the data attribute (data-select-text and data-select-values) of the currently clicked button, so below is a working snippet except for getting the data-select-values which is the problem because i dont know how to loop it along with the data-select-text so that the result of each select option will have values and text base from the split values of the data-select-text and data-select-values attribute, any ideas, help, suggestions, recommendations?
NOTE: currently, I could only able to use the attribute data-select-text as a select options values and text.
$(document).ready(function(){
$(document).on("click", "button", function(){
if($(this).attr("data-input-type").toLowerCase() === "select"){
var classList = $(this).attr('data-select-text').split(/\s+/);
var field = '<select>';
$.each(classList, function(index, item) {
field += '<option value="' + item.replace(/%/g, ' ') + '">' + item.replace(/%/g, ' ') + '</option>';
});
field += '</select>';
}
$("body").append(field);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button data-input-type="select" data-select-text="select%1 select%2 select%3" data-select-values="1 2 3">Create a select dropdown option</button>
You could create an array for the values, the same as so did for the text.
Make sure that the order in both data-select-text and data-select-values is the same. Then you can use the index in your $.each loop:
$(document).ready(function(){
$(document).on("click", "button", function(){
var elem = $(this);
if( elem.attr("data-input-type").toLowerCase() === "select" ){
var classList = elem.data('select-text').split(/\s+/),
valueList = elem.data('select-values').split(/\s+/),
field = '<select>';
$.each(classList, function(index, item) {
field += '<option value="' + valueList[index].replace(/%/g, ' ') + '">' + item.replace(/%/g, ' ') + '</option>';
});
field += '</select>';
}
$("body").append(field);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button data-input-type="select" data-select-text="select%1 select%2 select%3" data-select-values="1 2 3">Create a select dropdown option</button>
The result will be:
<select>
<option value="1">select 1</option>
<option value="2">select 2</option>
<option value="3">select 3</option>
</select>
Here is one way to do it, if I understand correctly. This code does not take into account different text or value lengths. It expects that the text length of options created is always equal to the values length being used.
$(document).ready(function () {
$(document).on("click", "button", function () {
if ($(this).attr("data-input-type").toLowerCase() === "select") {
var classList = $(this).attr('data-select-text').split(/\s+/);
var valueList = $(this).attr('data-select-values').split(' ');
var field = '<select>';
$.each(classList, function (index, item) {
field += '<option value="' + valueList[index] + '">' + item.replace(/%/g, ' ') + '</option>';
});
field += '</select>';
}
$("body").append(field);
})
});
Fiddle: http://jsfiddle.net/32qt0vn8/
I have the following code that append elements to the document if the corresponding radio button is checked. This works fine, however I need a way to remove the elements if the radio button is NOT checked.
Here is what I have so far?
// for each radio button
$('input[type=radio]').each(function(){
// if it is checked
if($(this).is(":checked"))
{
var cur = $(this).val();
// append an input text element only if it does not already exist
if(!$('#characterList input:text').is(function(i,e){ return e.value==cur && e.name=='data['+cur+']'; }))
{
$('#characterList').append('<input type="text" name="data[' + $(this).val() + ']" value="' + $(this).val() + '" />');
}
}
else
{
// otherwise remove element if radio button not checked
$('#characterList').remove('<input type="text" name="data[' + $(this).val() + ']" value="' + $(this).val() + '" />');
}
});
});
The .remove(...) does nothing at all. What am I doing wrong here?
remove() doesn't work like that. You have to provide a selector to select the element you wish to remove. This can be done like so:
$('#characterList').remove('input[value="' + $(this).val() + '"]');
Or, alternatively:
$('#characterList').find('input[value="' + $(this).val() + '"]').remove();
Furthermore, instead of using $(this).is(":checked") and $(this).val(), you can simply use:
if ( this.checked )
And:
var cur = this.value;
i am trying to call an element inside a json object, here is a part of the code
{
" academy": {
"business": {
"E-commerce": [
now i successed to call academy as the first element, by this code
$.getJSON("professorUnversityCollegeCourseData.js", function(property) {
$.each(property, function (key, value) {
$('#uni').add('<option value="'+ key + '" id="'+ count +'">'+ key +
'</option>').appendTo('#university-selection');
arrayUni[count] = key;
count++;
});
how can i get the "business" element now ?
Have you ever tried:
$.getJSON("professorUnversityCollegeCourseData.js", function(property) {
$.each(property, function (key, value){
$('#uni').add('<option value="'+ key + '" id="'+ count +'">'+ key + '</option>').appendTo('#university-selection');
arrayUni[count] = key;
count++;
alert(this.academy.business);//Or also this['academy']['business']
});
alert(property.academy.business);//Or also property['academy']['business']
});
I think what you should do is this:
$.getJSON("professorUnversityCollegeCourseData.js", function(property){
business = property.academy.business;
//-or-
business = property["academy"]["business"];
});
(according to the data you put up there.)
I assume this is what you are after
key.academy.business
It really is that simple, or :
key['academy']