loop through div with different elements - javascript

I generated elements and put them in MyDiv
$("#MyDiv").append('<input type=text class = "form-control" id=tb' + row.PropertyName + ' ' + 'value="Text' + row.PropertyName + '" />');
$("#MyDiv").append(' <input type="hidden" name="hid" value= "' + row.PropertyId + '">');
Now I need to extract the row.PropertyName and row.PropertyId
I need something like this:
var arrText = new Array();
$('#MyDiv > input[type = text]').each(function () {
var id = $(this).id.val();
var text = $(this).text.val();
var data = {
'id': id,
'text': text
}

I guess this is what you want.
$(function(){
var PropertyName = "pn1";
var PropertyId = "pn2";
$("#MyDiv").append('<input type="text" class = "form-control" id="tb"' + PropertyName + ' ' +
'value="Text' + PropertyName + '" />');
$("#MyDiv").append(' <input type="hidden" name="hid" value= "' + PropertyId + '">');
$('#MyDiv > input[type = "text"]').each(function(){
var id = $(this).val();
var text = $(this).next('input[type = "hidden"]').val();
var data = {
id: id,
text: text
}
alert(data.id + data.text);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="MyDiv"></div>

var arrText = [];
$('#MyDiv > input[type=text]').each(function () {
arrText.push({
'id': this.id,
'text': this.value
});
});
console.log( arrText );

Related

How can I replace a variable in one method from another method

I am working a project where I can add checkboxes but at first I make a textbox and then I press done and then the another button will replace that textbox with the value of that textbox.
When I have them in different methods the variable is not defined and when I put it in the same method it prints out in the console as twice the ids I need.
The first one below is the one that doubles the id - look at the console For both.
$("#addBtn").click(function() {
var lastField = $("#buildyourform div:last"); // Getting the id of #buildyourownform and getting the last div
var intId = (lastField && lastField.length && lastField.data("idx") + 1) || 1; // Changing the Id
const fieldWrapper = $("<div class=\"fieldwrapper\" id=\"field" + intId + "\"/>");
fieldWrapper.data("idx", intId);
// console.log(intId);
var fName = $("<input type=\"text\" class=\"fieldname\" />");
var ftype = $("<input type=\"checkbox\" class=\"giannisCheckbox\" />");
fieldWrapper.append(ftype);
fieldWrapper.append(fName);
$("#buildyourform").append(fieldWrapper);
$("#doneBtn").click(function() {
// $("#yourform").remove();
$("#buildyourform div").each(function() {
var id = "checkbox" + $(this).attr("id").replace("field", "");
console.log(id);
var label = $("<label for=\"" + id + "\">" + $(this).find("input.fieldname").first().val() + "</label>");
fName.replaceWith(label);
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" id="addBtn" value="Add" />
<input type="button" id="doneBtn" value="Done" />
<fieldset id="buildyourform"></fieldset>
$("#addBtn").click(function() {
var lastField = $("#buildyourform div:last"); // Getting the id of #buildyourownform and getting the last div
var intId = (lastField && lastField.length && lastField.data("idx") + 1) || 1; // Changing the Id
const fieldWrapper = $("<div class=\"fieldwrapper\" id=\"field" + intId + "\"/>");
fieldWrapper.data("idx", intId);
// console.log(intId);
var fName = $("<input type=\"text\" class=\"fieldname\" />");
var ftype = $("<input type=\"checkbox\" class=\"giannisCheckbox\" />");
fieldWrapper.append(ftype);
fieldWrapper.append(fName);
$("#buildyourform").append(fieldWrapper);
});
$("#doneBtn").click(function() {
// $("#yourform").remove();
$("#buildyourform div").each(function() {
var id = "checkbox" + $(this).attr("id").replace("field", "");
// console.log(id);
var label = $("<label for=\"" + id + "\">" + $(this).find("input.fieldname").first().val() + "</label>");
fName.replaceWith(label);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" id="addBtn" value="Add" />
<input type="button" id="doneBtn" value="Done" />
<fieldset id="buildyourform"></fieldset>
Try this
let $buildyourform = $("#buildyourform");
$("#addBtn").click(function() {
let intId = $buildyourform.children().length + 1;
$("#buildyourform").append(`
<div class="fieldwrapper" id="field${intId}">
<input type="checkbox" class="giannisCheckbox" />
<input type="text" class="fieldname" />
</div>
`);
});
$("#doneBtn").click(function() {
$buildyourform.children().each(function() {
let $checkbox = $(this).find('.giannisCheckbox');
let $fieldname = $(this).find('.fieldname');
let id = "checkbox" + $(this).attr("id").replace("field", "");
$checkbox.attr('id', id);
$fieldname.replaceWith(`<label for="${id}">${$fieldname.val()}</label>`);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" id="addBtn" value="Add" />
<input type="button" id="doneBtn" value="Done" />
<fieldset id="buildyourform"></fieldset>

I cannot add the class "unread" to the append content of a certain data-id

I want to add the "unread" class to an append content with a specific data-id. The following line of code works fine in the browser console. However, when the code is run it does not add the class "unread".
var idMessage = message[message.length-1].id;
$('#visitors').find('h5[data-id=' + idMessage + ']').addClass('unread');
The goal is to add "unread" in the following line of code:
$("#visitors").append('<h5 class="' + state + '" data-id=' + visitors[i].idSession + '>' + visitors[i].visitorOnline + '</h5>');
I will provide you with a code snippet
<div id="conexion-chat">
<button id="btn-conexion-chat" onclick="initWebSocket();">Iniciar chat</button>
</div>
<div id="display-chat" style="display: none;">
<div id="visitors"></div>
<br />
<textarea id="chatRoomField" rows="10" cols="30" readonly></textarea> <br/>
<input id="sendField" value="" type="text">
<button id="sendButton" onclick="send_message();">Enviar</button>
</div>
function initWebSocket(){
$('#conexion-chat').css('display', 'none');
$('#display-chat').css('display', '');
websocket = new WebSocket("ws://localhost:8080/o/echo");
websocket.onopen = function (event) {
websocket.send(json_user());
};
websocket.onclose = function(event) {
localStorage.clear();
console.log("DESCONECTADO");
};
websocket.onmessage = function(event) {
var message = event.data;
processMessage(message);
};
websocket.onerror = function(event) {
console.log("ERROR: " + event.data);
};
}
function visitorSelected(event){
var visitorSelected = $(event.target).data('id');
localStorage.setItem('visitorSelected', visitorSelected);
websocket.send(json_messages(visitorSelected, '${email}', '${read}'));
document.getElementById("chatRoomField").innerHTML = "";
}
function processMessage(message){
if(message == '${disconnected}'){
document.getElementById("chatRoomField").innerHTML += "El patrocinador no se encuentra conectado." + "\n";
}else {
var json_message = JSON.parse(message);
var visitorSelected = localStorage.getItem('visitorSelected');
if(json_message.hasOwnProperty('message') && message.length > 0){
var message = json_message.message;
var text = "";
if('${currentUserRol}' != '${rolPreferences}'){
for(var i=0; i<message.length; i++){
text += message[i].from + ": " + message[i].message + "\n";
document.getElementById("chatRoomField").innerHTML = text;
}
}else{
if(message[message.length-1].id == visitorSelected || message[message.length-1].idTo == visitorSelected){
for(var i=0; i<message.length; i++){
text += message[i].from + ": " + message[i].message + "\n";
document.getElementById("chatRoomField").innerHTML = text;
}
}else{
var idMessage = message[message.length-1].id;
$('#visitors').find('h5[data-id=' + idMessage + ']').addClass('unread');
}
}
}
if(json_message.hasOwnProperty('visitors') && json_message.visitors.length > 0){
var visitors = json_message.visitors;
var state;
$("#visitors h5").remove();
for (var i = 0; i < visitors.length; i++) {
state = (visitors[i].idSession == visitorSelected)? "selected" : "not-selected";
$("#visitors").append('<h5 class="' + state + '" data-id=' + visitors[i].idSession + '>' + visitors[i].visitorOnline + '</h5>');
}
if(visitorSelected == null){
$("#visitors h5:first-child").attr("class", "selected");
visitorSelected = $("#visitors h5:first-child").attr("data-id");
localStorage.setItem('visitorSelected', visitorSelected);
}
}
}
}
$('#visitors').on('click', 'h5.not-selected', visitorSelected);
*Note: The entire code has not been submitted, but a code snippet.
Thanks!
Regards!

Generate a multidimensional array for php post, using data attributes of inputs

I have set a code to generate dynamic tables to capture data, which will be used to send a message to the students regarding a timetable. Following generates the required user input form, so that the user can insert the data as required.
$(document).ready(function() {
var index = 1;
var tableindex = 0;
var daydd = '<select><option value="Saturday">Saturday</option><option value="Sunday">Sunday</option></select>';
$("#addRow").click(function() {
if (tableindex == 0) {
tableindex++;
$("#myTable").append("<tr data-day='" + tableindex + "'><td colspan=3>"+daydd+" " + tableindex + "</td><td><button class='dayclose' data-day='" + tableindex + "'>Close</button></td></tr>");
}
$("#myTable").append("<tr data-day='" + tableindex + "'><td>Day " + tableindex + "</td><td>row " + index + "</td><td><input type='text' data-clday='" + tableindex + "' data-subj='" + index + "' ></td><td><button class='subjclose' id='" + index + "'>Close</button></td></tr>");
index++;
});
$("#addtable").click(function() {
tableindex++;
$("#myTable").append("<tr data-day='" + tableindex + "'><td colspan=3>"+daydd+" " + tableindex + "</td><td><button class='dayclose' data-day='" + tableindex + "'>Close</button></td></tr><tr data-day='" + tableindex + "'><td>Day " + tableindex + "</td><td>row " + index + "</td><td><input type='text' data-clday='" + tableindex + "' data-subj='" + index + "' ></td><td><button class='subjclose' id='" + tableindex + "'>Close</button></td></tr>");
index++;
});
$('table').on('click', '.subjclose', function(e) {
e.preventDefault();
$(this).parents('tr').remove();
});
$('table').on('click', '.dayclose', function(e) {
e.preventDefault();
var closeday = $(this).attr("data-day");
$('tr[data-day="' + closeday + '"]').remove();
$(this).parents('tr').remove();
});
//$('.row-container[data="product_id"]').remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<table id="myTable">
</table>
<input type="button" id="addRow" value="add subject" />
<input type="button" id="addtable" value="add day" />
<input type="button" id="submit" value="Send Data" />
Now I am trying to capture data to be sent to a php script, so that it can send the message to a selected set of students. My message would be as follows; (consider rows 3,4,6,9 as deleted in this scenario)
Saturday Subjects
Row 1 data
Row 2 data
Sunday Subjects
Row 5 data
Row 7 data
Monday Subjects
Row 8 data
Row 10 data
I am trying to run a for each loop for this in my php script, but I do not have any idea how to achieve this with the data attributes.
How can I generate a multidimensional array to be sent to a php script using the data attributes of inputs so that it can be used to generate a foreach loop?
You can use the JQuery function like this
$.fn.onAddDefaultValue = function (options) {
// This is the easiest way to have default options.
var settings = $.extend({
// These are the defaults.
data: '',
profile_main_div_id: '',
server_div_id: '',
addi_id : '',
confirm_btn_id: ''
}, options);
$(settings.data).each(function(idx,obj){
var item_id = obj.item_id;
var item_title = obj.item_title;
// server pratik - 10112017 location widget interaction
var isLocationExist = false;
$("#"+settings.server_div_id).children().each(function () {
var child_div = $(this);
var localtion_value = child_div.find("span").text();
if (localtion_value == item_title) {
//child_div.find("span").css("border", "1px solid #f16262");
isLocationExist = true;
//return false;
}else {
//child_div.find("span").css("border", "0px solid #f16262");
}
});
if (!isLocationExist) {
var input_value = item_title;
var newTextBoxDiv = $(document.createElement('div'))
.attr({"class": 'customcheckbox',"style":'margin: 0px 0px 10px;'});
var chk_id = item_id;
newTextBoxDiv.after().html('<input type="checkbox" checked name="remember" id="'+chk_id+'" value="user_profile_remember_me-no">'+
'<input type="hidden" class="server_item_id" value="'+item_id+'" />'+
'<label style="float: right;position: relative;margin-right: 10px;border: 1px solid #000000;border-radius: 0px" for="'+chk_id+'">'+
'<div class="input-label"></div>'+
'</label>'+
'<span style="padding-left: 5px;" class="my-label1">'+input_value+'</span>');
newTextBoxDiv.appendTo("#"+settings.server_div_id);
//$("#"+settings.addi_id).slideUp();
//$(this).closest('#'+settings.profile_main_div_id).removeClass("additional-field-open");
// add new item
} else {
$('#'+settings.server_div_id).children().each(function () {
var child_div_appearance = $(this);
var title_v = $(this).find("span").text();
var status_v = $(this).find("input[type='checkbox']").prop("checked");
if((item_title == title_v) && (!status_v)){
$(this).find("input[type='checkbox']").click();//attr("checked",false)
// break loop
// return false;
}
});
}
$("#"+settings.confirm_btn_id).click();
//$("#"+settings.server_div_id).addClientNote({});
});
};
and remove added element like this
$.fn.removeDiagnosisValue = function (options) {
// This is the easiest way to have default options.
var settings = $.extend({
// These are the defaults.
title: ''
}, options);
$(this).children().each(function () {
var child_div = $(this);
var div_buttons = child_div.find("div");
var i = 0;
$(div_buttons).children().each(function () {
// delete icon
var child_span = $(this);
if (child_span.attr('name') == "delete") {
var img_delete = child_span.find("img");
img_delete.click(function () {
child_div.remove();
});
// break loop
return false;
}
});
});
};

Cannot select a button which appended dynamically in jQuery

I use getJSON function in jQuery and append the retrieved result in the form of button in the DOM. however I cannot use the selector on the appended DOM.
here is my script:
$.getJSON("http://example.com/checkDiary.php?babyID=" + localStorage.getItem("babyRegNo"), function(data) {
if (data.indexOf("noDiary") > -1) {
document.getElementById("diaryList").innerHTML = "<p>Your baby currently has no diary entry.</p>";
} else {
var appendedText = '';
$.each(data, function(){
var diaryID = this.diary_id;
var dateAdded = this.date;
appendedText = appendedText + '<p><button type="button" class="diaries" value ="' + diaryID + '">' + dateAdded + '</button></p>';
})
document.getElementById("diaryList").innerHTML = appendedText;
}
})
this is what i use to select:
$(':button.diaries').click(function(){});
but it seems not working. however when I put a dummy button with the same class in the HTML body, it is selected perfectly. Can you guys give me any suggestion?
#Kelvin Aliyanto ....So the solution will be like this
<script src="jquery-1.7.2.min.js" type="text/javascript"></script>
<script>
$(function(){
$.getJSON("http://example.com/checkDiary.php?babyID=" + localStorage.getItem("babyRegNo"), function(data) {
if (data.indexOf("noDiary") > -1) {
document.getElementById("diaryList").innerHTML = "<p>Your baby currently has no diary entry.</p>";
} else {
var appendedText = '';
$.each(data, function(){
var diaryID = this.diary_id;
var dateAdded = this.date;
appendedText = appendedText + '<p><button type="button" class="diaries" value ="' + diaryID + '">' + dateAdded + '</button></p>';
})
document.getElementById("diaryList").innerHTML = appendedText;
}
});
$('div').on('click', '.diaries', function(event){
alert("Hi");
}) ;
});
</script>
<div id="diaryList"></div>
check your code is after document ready
$(document).ready(function(){ //your code here });
and use
$('button.diaries').on(click , function(){})
instead of .click

Splitting an array

I have two javascript functions, the first one is working, teh second is working but not echoing the correct value in the hidden inputs.
Ive manage to get the last hidden input value correct but I'm not sure how
var customTicketsArr = Array();
function EditEventAddTicket(){
alertWrongTime = false;
var TicketName = jQuery("#ticketname").val();
var TicketPrice = jQuery("#ticketprice").val();
var ticketquantity = jQuery("#ticketquantity").val();
var storeString = "TicketName" + TicketName + "TicketPrice" + TicketPrice + "Quantity" + ticketquantity + '';
customTicketsArr.push(storeString);
EditEventUpdateTickets(true);
}
function EditEventUpdateTickets(fade){
jQuery("#custom_tickets_string").val(customTicketsArr);
var output = "";
var style = "";
for (i = customTicketsArr.length-1; i >= 0; i--){
ticketname = customTicketsArr[i].split("TicketName");
ticketprice = customTicketsArr[i].split("TicketPrice");
ticketquantity = customTicketsArr[i].split("Quantity");
if(fade){
if (customTicketsArr.length - 1 == i){
style = "display: none; ";
var fadeInDiv = i;
} else {
style = "";
}
}
if (i % 2 == 1) { style += "background-color: #660000; "}
html = "<div id='customticket" + i + "' class='customeventbase' style='" + style + "'>";
html += '<input type="hidden" name="customTicketid[' + i + '][Name]" id="customticketName' + i + '" value="'+ ticketname + '" />';
html += '<input type="hidden" name="customTicketid[' + i + '][Price]" id="customticketPrice' + i + '" value="' +ticketprice[1] +'" />';
html += '<input type="hidden" name="customTicketid[' + i + '][Quantity]" id="customticketQuantity' + i + '" value="'+ ticketquantity[1] +'" />';
html += '<button class="customeventdel" type="button" onClick="EditEventRemoveDate(' + i + ')"></button>';
html += '<div class="clear"></div>';
html += '</div>\n';
output += html;
}
output += "<input type='hidden' id='custom_ticket_info' name='custom_ticket_info' value='" + customTicketsArr + "' />";
jQuery("#custom_ticket_container").html(output);
if(fade){
setTimeout("EditEventfadeInDiv(" + fadeInDiv +")", 10);
}
}
this outputs:
<div style="background-color: #660000; " class="customeventbase" id="customticket1">
<input type="hidden" value=",testTicketPrice50Quantity44" id="customticketName1" name="customTicketid[1][Name]">
<input type="hidden" value="undefined" id="customticketPrice1" name="customTicketid[1][Price]">
<input type="hidden" value="44" id="customticketQuantity1" name="customTicketid[1][Quantity]">
<button onclick="EditEventRemoveDate(1)" type="button" class="customeventdel"></button>
<div class="clear"></div></div>
the values for the first two hidden fields are incorrect
They're not incorrect values - split() is doing exactly what it is supposed to - returning an array of substrings after removing the separator.
With your string structure, splitting on TicketName will give you two strings - the substring before the separator and the substring after - TicketName itself is not included.
Thus, for the string "TicketNametestTicketPrice50Quantity44", you will get "" and "testTicketPrice50Quantity44" when you split on "TicketName" . Splitting the same string on TicketPrice will give you "TicketNametest" and "50Quantity44".
I'd suggest putting objects into your array instead -
var storeObject = {
"TicketName" : TicketName,
"TicketPrice" : TicketPrice,
"Quantity" : ticketquantity
};
customTicketsArr.push(storeObject);
You can then get back the data as:
for (i = customTicketsArr.length-1; i >= 0; i--){
var currentObject = customTicketsArr[i];
var ticketname = currentObject.TicketName;
var ticketprice = currentObject.TicketPrice;
var ticketquantity = currentObject.Quantity;
//do other stuff here
}
why do you save it as a string? I would recommend storing it in an object:
function EditEventAddTicket(){
alertWrongTime = false;
var TicketName = jQuery("#ticketname").val();
var TicketPrice = jQuery("#ticketprice").val();
var ticketquantity = jQuery("#ticketquantity").val();
var ticket = {"TicketName": TicketName, "TicketPrice": TicketPrice, "Quantity": ticketquantity};
customTicketsArr.push(ticket);
EditEventUpdateTickets(true);
}
and then you can simply load the data:
for (i = customTicketsArr.length-1; i >= 0; i--){
ticketname = customTicketsArr[i].TicketName;
ticketprice = customTicketsArr[i].TicketPrice;
ticketquantity = customTicketsArr[i].Quantity;
// ...
}
Why not just make a two dimensional array?
var customTicketsArr = Array();
function EditEventAddTicket() {
customTicketsArr.push({
'name' : jQuery("#ticketname").val(),
'price' : jQuery("#ticketprice").val(),
'qty' : jQuery("#ticketquantity").val()
});
}

Categories

Resources