I need to split an array into an JSON array which should be following pattern.
{{"url":url, "north":True "side":True}, {"url":url, "north":False, "side":True}}
I get the url parameter with this code. As you can see here, this code displays 3 checkboxes where you can select if the picture is north, on the side or if you want to select it.
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
xmlDoc = xmlHttp.responseXML;
pictureTemp = [document.getElementById("imgfilename")];
$('.login-form').append('<button onclick="sendAuswahl()">Send</button><br>');
for (var i = 0; i < xmlDoc.getElementsByTagName("imgfilename").length; i++) {
pictureTemp[i] = xmlDoc.getElementsByTagName("imgfilename")[i].childNodes[0].nodeValue;
$('.login-form').append('<input type="checkbox" name="north" value="North"><input type="checkbox" name="orientation" value="Side"><input type="checkbox" name="url" value='+ pictureTemp[i]+'><img src='+ pictureTemp[i]+' width="50%"></br>');
};
}
To get all ticked checkboxes, I use this code:
var arrayUrl = $("input[name='url']:checked").map(function(){
return this.value;
}).get()
var arrayNorth = $("input[name='north']:checked").map(function(){
return "True";
}).get()
var arrayOrientation = $("input[name='orientation']:checked").map(function(){
return "True";
}).get()
To convert the selection to a JavaScript object and to get the pattern which I described above, I use this:
var picture = {
"url" : arrayUrl,
"North" : arrayNorth,
"Side" : arrayOrientation
};
But when I alert the value of a selected image I get this:
{"url":http://www.example.com, "north":True "side":True}
And when I select 2 images I get this:
{"url":http://www.example.com, http://www.example2.com, "north":True "side":False}
Instead of this:
{{"url":http://www.example.com, "north":True "side":False}, {"url":http://www.example2.com, "north":False, "side":True}}
So my question is now: How can I adept the values in the pattern which I've described above?
var picture = [];
$.each(arrayUrl, function(index,val) {
val = {
"url" : val,
"North" : arrayNorth[index],
"Side" : arrayOrientation[index]
};
picture.push(val);
});
var picture = [];
$(arrayUrl).each(function(index) {
picture.push({
"url": arrayUrl[index],
"North": arrayNorth[index],
"Side": arrayOrientation[index]
});
});
Related
I will post the part of a function that is adding numbers that are clicked into selected input field.
So, I need to separate it with a comma (,). I tried some of the examples but it seems not to be working on the function that I wrote.
var rowRange = 'abcdefghijklmnopqrstuvwxyz'.split('');
var $cart = $('#seats'),
$counter = $('#counter'),
sc = $('#seat-map').seatCharts({
map: [
'aaaaa__aaaaa',
'aaaaa__aaaaa'
],
naming : {
top : false,
getLabel : function (character, row, column) {
return rowRange[row - 1].toUpperCase() + column;
},
},
click: function () {
if (this.status() === 'available') {
$('#seats').split(",")
.attr('id', 'cart-item-'+this.settings.id)
.val(this.settings.label)
.appendTo($cart);
$counter.text(sc.find('selected').length+1);
return 'selected';
});
});
Seat is a input field where comma needs to be added after every click on any number.
.split(",")
when I remove this part the code works like it should, but without adding comma.
.split() doesn't work on jquery objects. Instead use it on the values in your select.
Here is an example on how it could work.
$selected = $('#selected');
$(".seat").on("click", function() {
const cur = $selected.val();
const valToInsert = $(this).text();
$selected.val(cur.length === 0 ? valToInsert : cur.split(',').concat(valToInsert).join(','));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="selected">
<button class="seat">a</button>
I have a post ajax that return retorno1 and just to get it simple i put their output as string value as ajax posted like the example .. then I need to add more than 1 option that the value is 0 so I need to say if the value is 0 show the selected item "NON" and if the value other so show it and select it.
I'm using setAttribute("selected", "selected") but I know it's wrong, so what is the correct code to add attribute to this string?
var i = 0;
var returno1 = "<option value='21'>Hello</option><option value='22'>Bye</option>";
var pre = retorno1 + '<option value="0">------ N/A ------</option>';
var count = $($.parseHTML(pre)).filter('option').length;
var dep_dr = $("#departamento_drop option:selected").val();
$.each($.parseHTML(pre),function(i,item){
var val_drop =($(item).val());
var text_drop =($(item).html());
if (val_drop == dep_dr){
jQuery("#departamento_drop").html(pre).setAttribute("selected", "selected");
}else if(dep_dr == "0"){
jQuery("#departamento_drop").html(pre).setAttribute("selected", "selected");
}
})
Working fiddle
Try to use attr() or prop() to set or get attribute to elements, check example bellow :
jQuery("#departamento_drop").empty();
$.each($.parseHTML(pre),function(i,item){
var current_itme=$(item);
var val_drop =current_itme.val();
var text_drop =current_itme.html();
if (val_drop == dep_dr || dep_dr == "0"){
current_itme=current_itme.attr("selected", "selected");
}
jQuery("#departamento_drop").append(current_itme);
})
Hope this helps.
Why do you need use strings? Use objects insted.
var values = [{val:33, title:'Hi'},{val:34, title:'Bue'},{val:0, title:'-------NA-------'}],
selected = 34;
values.forEach(function(item){
$('#dd').append($('<option>', {value:item.val, text:item.title, selected: item.val==selected}));
})
I'm trying to make a quiz powered by jQuery (and maybe JSON), with the values stored in a database. It works fine so far, but I'd like to hide the radio buttons (CSS: display: none) and make each question look like a button (much easier to select than a tiny radio button).
However, when I do this, the following JavaScript doesn't work, and the quiz isn't scored.
var imgpath = "/images/sections/test/";
var jsonpath = "/2b/inc/pages/quiz-php/json/";
var jsonfile = "key";
$(document).ready(function(){
//Make sure radio buttons are not disabled or checked (helpful when refreshing)
$("input[type='radio']").attr("disabled", false);
$("input[type='radio']").attr("checked", false);
$(".submit").click(function(e){
e.preventDefault();
//Check the quiz results
checkQuiz();
});
//Build the json filename
jsonfile = $("#quiz").attr("rel")+".php";
});
//Load json file
function getData(update){
$.getJSON(jsonpath+jsonfile, function(json){
//Execute the callback
update(json);
}).error(function(){alert("error");});
}
function checkQuiz(){
$(".submit").remove();
getData(function(data){
var ans = data.key;
var result = {};
$(".Question").each(function(){
//Get the question id
var _q = $(this).attr("id");
//Get the selected answer class
var _a = $("#"+_q+" input:checked").closest("li").attr("class");
//Add the values to the result object
result[_q] = _a;
//Compare the selected answer with the correct answer
if(ans[_q]==_a){
$(this).addClass("correct");
}else{
$(this).addClass("wrong");
}
});
//Build the feedback
var fdbck = "You got "+$(".correct").length+" out of "+$(".Question").length+" correct. "
if($(".correct").length==0){
fdbck += "Better luck next time.";
}else if($(".correct").length>$(".Question").length/2){
fdbck += "Good job!";
}else{
fdbck += "Not bad.";
}
$(".feedback").text(fdbck);
$(".feedback").show();
});
}
So I wondered if there's some way to record scores besides a radio button. I created a JSFiddle # http://jsfiddle.net/9j7fz99w/6/ to illustrate how I'm using jQuery and CSS to style correct and incorrect answers. Is there a way to modify the code above to similarly recognize correct questions based on their "selection," rather than a radio button?
Just a small example using a JS questions Array with Objects
var $quizEl = $("#quizEl");
var $submit = $("#submit");
var quiz = [
{ // obj
"Q" : "What color is the Sun?",
"A" : ["Red", "Black", "Yellow"],
"C" : 2
},{
"Q" : "What color is an Elephant?",
"A" : ["Gray", "Blue", "Yellow"],
"C" : 0 // zero indexed!
},{
"Q" : "What color is the Sea?",
"A" : ["Fuchsia", "Blue", "Gold"],
"C" : 1
}
];
var qNum = quiz.length;
// FUNCTION THAT CREATES AND APPENDS AN `UL` TO `DIV #quizEl`
function generateQuestion( obj, idx ) {
var html = "<h2>"+ obj.Q +"</h2><ul>";
for (var i=0; i<obj.A.length; i++) {
html += "<li>"+
"<label>"+
"<input type='radio' name='"+ idx +"' value='"+i+"'>"+
obj.A[i] +"</label>"+
"</li>";
}
$quizEl.append( html+"</ul>" );
}
// GENERATE ALL QUESTIONS:
for(var i=0; i<qNum; i++) {
generateQuestion( quiz[i], i ); // quiz[i] is the {QAC} object
}
$quizEl.on("change", ":radio", function(){ // Record User choice (U property)
quiz[this.name].U = this.value; // set 0,1,2 to the new U property {QACU}
});
$submit.on("click", function(e){
e.preventDefault();
console.log( quiz ); // To test how it looks
// Check if user answered them all:
for(var i=0; i<qNum;i++){
if(!quiz[i].hasOwnProperty("U")){ // User did not answered if "U" property doesn't exists
return alert("Please,\nanswer the question "+ (i+1) +":\n"+ quiz[i].Q );
}else{ // Add classes...
$("ul").eq(i).find(":checked").closest("li")
.addClass( +quiz[i].U === quiz[i].C ? "correct":"wrong");
}
}
// Finally colour them!
$(".correct").css({background:"green"});
$(".wrong").css({background:"red"});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="quizEl"></div>
<input id="submit" type="submit">
I'm new to JS. I'm trying to delete the parent node with all the children by clicking a button. But the console tells me that undefined is not a function. What am I missing?
Fiddle:
http://jsfiddle.net/vy0d8bqt/
HTML:
<button type="button" id="output">Get contacts</button>
<button type="button" id="clear_contacts">clear contact</button>
<div id="output_here"></div>
JS:
// contact book, getting data from JSON and outputting via a button
// define a JSON structure
var contacts = {
"friends" :
[
{
"name" : "name1",
"surname" : "surname1"
},
{
"name" : "name2",
"surname" : "surname2"
}
]
};
//get button ID and id of div where content will be shown
var get_contacts_btn = document.getElementById("output");
var output = document.getElementById("output_here");
var clear = document.getElementById("clear_contacts");
var i;
// get length of JSON
var contacts_length = contacts.friends.length;
get_contacts_btn.addEventListener('click', function(){
//console.log("clicked");
for(i = 0; i < contacts_length; i++){
var data = contacts.friends[i];
var name = data.name;
var surname = data.surname;
output.style.display = 'block';
output.innerHTML += "<p> name: " + name + "| surname: " + surname + "</p>";
}
});
//get Children of output div to remove them on clear button
//get output to clear
output_to_clear = document.getElementById("output_here");
clear.addEventListener('click', function(){
output_to_clear.removeNode(true);
});
You should use remove() instead of removeNode()
http://jsfiddle.net/vy0d8bqt/1/
However, this also removes the output_to_clear node itself. You can use output_to_clear.innerHTML = '' if you like to just delete all content of the node, but not removing the node itself (so you can click 'get contacts' button again after clearing it)
http://jsfiddle.net/vy0d8bqt/3/
You want this for broad support:
output_to_clear.parentNode.removeChild(output_to_clear);
Or this in modern browsers only:
output_to_clear.remove();
But either way, make sure you don't try to remove it after it has already been removed. Since you're caching the reference, that could be an issue, so this may be safer:
if (output_to_clear.parentNode != null) {
output_to_clear.remove();
}
If you were hoping to empty its content, then do this:
while (output_to_clear.firstChild) {
output_to_clear.removeChild(output_to_clear.firstChild);
}
I think using jQuery's $.remove() is probably the best choice here. If you can't or don't want to use jQuery, The Mozilla docs for Node provides a function to remove all child nodes.
Element.prototype.removeAll = function () {
while (this.firstChild) { this.removeChild(this.firstChild); }
return this;
};
Which you would use like:
output_to_clear.removeAll();
For a one-off given the example provided:
while (output_to_clear.firstChild) { output_to_clear.removeChild(output_to_clear.firstChild); }
I have large form mainly drop down lists and checkboxes. Checkboxes are created dynamically so i don't know their id's before they are created. I use drop down onChange event to do create them on the fly.
How can i loop trough the form and get all the checkboxes that are checked, that is their id and their value? I need to do this only for check boxes that are checked. All checkboxes share the same name, that is: categoriesfilters[]. Currently i have on click event on the checkbox which invoke the javascript function.
Here is the code:
function update_number_of_adds_found(field_dropdown,selected_value) {
selected_value="";
var addtypeid = $("#addtypeid").val();
// trying to store the values of the checkboxes
$(this).find("input[type=checkbox]:checked").each(
function() {
var id = $(this).attr('id');
var value = $(this).val(); // or maybe attr('value');
// the data is stored, do whatever you want with it.
alert(value);
}
);
var selected_value = {
addtypeid: addtypeid,
// need to add the ids and the values here as well
};
var url = "<?php echo site_url('search/findNumberOfAdds'); ?>";
$.post(url, selected_value, function(r){
if(r) {
$('#totalNumOfAdds').empty();
$("#totalNumOfAdds").append(r.result);
} else {
// alert(selected_value);
}
}, 'json')
}
Regards, John
Try this :
var categories = [];
$("input[name='categoriesfilters[]']:checked").each(
function() {
var id = $(this).attr("id");
var value = $(this).val();
categories[categories.length] = {id : value};
}
);
console.log(categories);
$.post(url, categories, function(r){
...
Try this :
$('form').submit(function(){
$(this).find("input[type=checkbox]:checked").each(
function() {
var id = $(this).attr('id');
var value = $(this).val(); // or maybe attr('value');
// the data is stored, do whatever you want with it.
}
);
});
I guess you want to check that on form submit.
var arr = [];
$('input[name^="categoriesfilters"]:checked').each(function() {
var obj = {
id: $(this).attr('id');
value: $(this).val();
};
arr.push(obj);
});
console.log(arr); // show us the array of objects
Would you like to use Jquery?
Add a class to each of the checkbox i.e "class_chk";
$(function(){
$('.class_chk').each(function(){
if($(this).is(':checked')){
var id = $(this).attr('id');
var val = $(this).val();
alert("id = "+id+"---- value ="+val);
}
});
});
The above way you can get all the check box id and value those are checked.
Thanks..