I've created a comment system that posts comments in an ordered list. My requirememnts were to add hide/show toggle function to each comment.
Currently, the toggle function only works on the first comment (even when you try to click on 2nd, 3rd, etc.)
I've tried to use querySelectAll, but it didn't work for me. What am I doing wrong?
<div class="textbox">
<h3>Leave comments</h3>
<label for=msg>Name</label><br>
<input type=text id=fname> <br>
<label for=msg>Content</label><br>
<textarea id=msg> </textarea>
<br>
<input type=button onclick="postcomments()" value="Send" />
<input type="reset" value="Reset" />
<ol id="showcomments" style="max-width:200px; font-size:12px; padding-left:10px;">
</ol>
</div>
<script>
var ans = [];
function postcomments() {
var fname = document.getElementById("fname").value;
var msg = document.getElementById("msg").value;
var lastpos = ans.length;
var current = new Date();
console.log(current);
var time = current.getHours() + ":" + (current.getMinutes() < 10 ? '0' : '') + current.getMinutes();
var date = current.getDate() + "." + (current.getMonth() + 1) + "." + current.getFullYear();
var i = 0;
ans[lastpos] = '<img src="Media/minusicon.png" alt="minusicon" onclick="toggle(document.getElementById("txt"))" style="width:8%;" id="plusminusicon">' + " " + "Sent By" + " " + '' + fname + '' + " " + " In" + " " + date + " " + "At" + " " + time + '<br>' + '<span id="txt" class="toggle_panel">' + msg + '</span>' + '<br>' + '-------------------------------';
var ol = document.getElementById("showcomments");
ol.innerHTML = "";
for (var i = 0; i < ans.length; i++) {
ol.innerHTML += "<li id=" + (i + 1) + ">" + ans[i] + "</li>";
}
}
function toggle(x) {
if (x.style.display === "none") {
x.style.display = "block";
document.getElementById("plusminusicon").src = "Media/minusicon.png";
} else {
x.style.display = "none";
document.getElementById("plusminusicon").src = "Media/plusicon.png";
}
}
</script>
You have always the same id for all "txt" span, so the browser change always the first.
If you don't want change much of your code the simpliest solution is add the lastpost variable to the span id and to the parameter of toggle function.
Here the changes to do:
ans[lastpos] = '<img src="Media/minusicon.png" alt="minusicon" onclick="toggle(' + lastpos + ')" style="width:8%;" id="plusminusicon' + lastpos + '">' + " " + "Sent By" + " " + '' + fname + '' + " " + " In" + " " + date + " " + "At" + " " + time + '<br>' + '<span id="txt' + lastpos + '" class="toggle_panel">' + msg + '</span>' + '<br>' + '-------------------------------';
function toggle(x) {
let comment = document.getElementById("txt" + x);
let icon = document.getElementById("plusminusicon" + x);
if (comment.style.display === "none") {
comment.style.display = "block";
icon.src = "Media/minusicon.png";
} else {
comment.style.display = "none";
icon.src = "Media/plusicon.png";
}
}
To bind click listeners to dynamically added elements, you can use event delegation.
document.addEventListener('click', function(e) {
if (e.target && e.target.classList.contains('comment')) {
// do something
}
})
jQuery makes it even easier.
$(document).on('click','.comment',function(){ //do something })
And here's a jsfiddle link to the complete code example. https://jsfiddle.net/ep2bnu0g/
Related
I want to create a basic search engine that searches students already existing in an array of objects by first name and last name and if it finds a student named that way enlist it on the page, and if it doesn't write on the page it doesn't exist. but when I have 2 people with the same first name, it gives me both outcome of the if statement. can someone help, please
searchButton.addEventListener("click", function () {
userSearch = searchInput.value;
for (i = 0; i < allStudents.length; i++) {
student = allStudents[i];
if(userSearch.toLowerCase() === student.firstName.toLowerCase() ||
userSearch.toLowerCase() === student.lastName.toLowerCase() ||
userSearch.toLowerCase() === student.firstName.toLowerCase() + " " + student.lastName.toLowerCase() ||
userSearch.toLowerCase() === student.lastName.toLowerCase() + " " + student.firstName.toLowerCase()) {
outputDiv.innerHTML += "<h2> Student: " + student.firstName + " " + student.lastName + "</h2><br>" +
"Age: " + student.age + "<br>" +
"Eye Color: " + student.eyeColor + "<br>" +
"Hair Color: " + student.hairColor + "<br>" +
"Programming Skills: " + student.programmingSkills
searchInput.value = "";
} else {
searchInput.value = "";
outputDiv.innerHTML += "<h2>The student you searched for is not in out database</h2>"
}
}
});
You might want to change your logic as you have two tasks:
Find if the student exists
Display students if available else show message
You can use a variable (found) to keep track of whether any students were found in allStudents, that way you won't have to worry about the else condition executing more than once
let allStudents = [{
firstName: "George",
lastName: "A"
}, {
firstName: "George",
lastName: "B"
}]
searchButton.addEventListener("click", function() {
outputDiv.innerHTML = "";
userSearch = searchInput.value;
var found = false;
for (i = 0; i < allStudents.length; i++) {
student = allStudents[i];
if (userSearch.toLowerCase() === student.firstName.toLowerCase() ||
userSearch.toLowerCase() === student.lastName.toLowerCase() ||
userSearch.toLowerCase() === student.firstName.toLowerCase() + " " + student.lastName.toLowerCase() ||
userSearch.toLowerCase() === student.lastName.toLowerCase() + " " + student.firstName.toLowerCase()) {
outputDiv.innerHTML += "<h2> Student: " + student.firstName + " " + student.lastName + "</h2><br>" +
"Age: " + student.age + "<br>" +
"Eye Color: " + student.eyeColor + "<br>" +
"Hair Color: " + student.hairColor + "<br>" +
"Programming Skills: " + student.programmingSkills
found = true;
}
}
if (!found)
outputDiv.innerHTML = "<h2>The student you searched for is not in out database</h2>";
searchInput.value = "";
});
<input id="searchInput" value="George" />
<button id="searchButton">search</button>
<div id="outputDiv"></div>
You need to rearrange the check to see if it's found or not. You are outputting "that student was not found in our database" INSIDE the loop of students, so it's outputting that text even if another result (in the loop) WAS found. I have corrected that issue by moving the check (for if a student was found) outside of the loop and using a variable to track that. I also changed some things so that you aren't reformatting names toLowerCase() in every loop or having to locate a DOM element.
searchInput = document.getElementById("search_text"),
searchButton = document.getElementById("SearchButton"),
outputDiv = document.getElementById("outputdiv");
searchButton.addEventListener("click", function () {
var userFound = false;
userSearch = searchInput.value;
studentLen = allStudents.length;
outputDiv.innerHTML = "";
for (i = 0; i < studentLen; i++) {
student = allStudents[i];
userSearch = userSearch.toLowerCase();
var fn = student.firstName.toLowerCase(),
ln = student.lastName.toLowerCase();
if(userSearch === fn || userSearch === ln || userSearch === fn + " " + ln || userSearch === ln + " " + fn) {
outputDiv.innerHTML += "<h2> Student: " + student.firstName + " " + student.lastName + "</h2><br>" +
"Age: " + student.age + "<br>" +
"Eye Color: " + student.eyeColor + "<br>" +
"Hair Color: " + student.hairColor + "<br>" +
"Programming Skills: " + student.programmingSkills
searchInput.value = "";
userFound = true;
}
}
if(!userFound){
outputDiv.innerHTML += "<h2>The student you searched for is not in out database</h2>";
}
});
Working fiddle with HTML/JS both included:
https://jsfiddle.net/Ltkacgn4/
So I have this command that's supposed to display a player's stats if it's found and says player not found otherwise. After I search a player and go to the previous screen, I get "player not found". I thought it was because my loop continues running after the player is found and my boolean becomes false, so I added a break statement. Won't work
function Search(Table, Stat1, Stat2, Stat3, Stat4, Stat5) {
onEvent("Search2.btn", "click", function() {
readRecords(Table, {}, function(records) {
var SearchPlayer = getText("text_input1");
var found = false;
for (var i = 0; i < records.length; i++) {
if ((records[i]).Player == SearchPlayer) {
setScreen("DisplaySearch");
setText("label3", records[i].Player + " Stats" + "\n" + records[i][Stat1] + " " + Stat1 + "\n" + records[i][Stat2] + " " + Stat2 + "\n" + records[i][Stat3] + " " + Stat3 + "\n" + records[i][Stat4] + " " + Stat4 + "\n" + records[i][Stat5] + " " + Stat5 + "\n");
setText("text_input1", "");
setText("label5", "");
found = true;
break;
} else if ((found == false)) {
setText("label5", "Player Not Found");
}
}
});
});
Below is my code which creates the textboxes dynamically in modal pop up each time when i click add button and removes the text boxes in that row each time when i click remove button which is working fine till here the problem is i have the javascript function which validates the month date and year in text box that if if we give any number greater than 12 it shows message that month should be less than 12 similarly for date also it will accept till 31 but if it is greater than 31 it shows error message and similarly year also but this is done for our asp text boxes how can i make this javascript function to work in modal pop where the textboxes are created dynamically
<script type="text/javascript">
function GetDynamicTextBox(value) {
if (value == "") {
FillDropdown()
return '<input name = "DynamicTextBox" value = "' + value + '" placeholder="MM/DD/YYYY"></input> <select name = "DynamicTextBox" >"' + Hours + '"</Select><b>:</b><select name = "DynamicTextBox">"' + Min + '"</Select>' +
' <input id="btnAdd123" type="button" value="Add" onclick="AddTextBox()" /><input type="button" value="Remove" onclick = "RemoveTextBox(this)" />'
//Min = "";
// Hours = "";
//
}
}
var HHEdit = "";
var MMEdit = "";
function GetDynamicTextBox1(value) {
values = value.split(' ');
one = values[0];
two = values[1];
values = two.split(':');
three = values[0];
Four = values[1];
HHEdit = three;
MMEdit = Four;
FillDropdown()
return '<input name = "DynamicTextBox" value = "' + one + '" placeholder="MM/DD/YYYY"></input> <select name = "DynamicTextBox" >"' + Hours + '"</Select><b>:</b><select name = "DynamicTextBox">"' + Min + '"</Select>' +
' <input id="btnAdd123" type="button" value="Add" onclick="AddTextBox()" /><input type="button" value="Remove" onclick = "RemoveTextBox(this)" />'
// $('.DynamicTextBox').val(one);
}
function AddTextBox() {
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function AddTextBox1() {
var inputCount = document.getElementById('TextBoxContainer').getElementsByTagName('input').length;
if (inputCount == "0") {
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var values = eval('<%=Values%>');
if (values != null) {
var html = "";
for (var i = 0; i < values.length; i++) {
html += "<div>" + GetDynamicTextBox1(values[i]) + "</div>";
}
document.getElementById("TextBoxContainer").innerHTML = html;
}
}
var Hours = "";
var Min = "";
function FillDropdown() {
for (var i = 0; i < 24; i++) {
if (i >= 0 && i <= 9) {
if (HHEdit != "" && HHEdit == i) {
Hours += '<option value="' + i + '" selected="selected">' + " 0" + i + " " + '</option>'
}
else {
Hours += '<option value="' + i + '">' + " 0" + i + " " + '</option>';
}
}
else {
if (HHEdit != "" && HHEdit == i) {
Hours += '<option value="' + i + '" selected="selected">' + " " + i + " " + '</option>';
}
else {
Hours += '<option value="' + i + '">' + " " + i + " " + '</option>';
}
}
}
for (var i = 0; i < 60; i++) {
if (i >= 0 && i <= 9) {
if (MMEdit != "" && MMEdit == i) {
Min += '<option value="' + i + '" selected="selected">' + " 0" + i + " " + '</option>';
}
else {
Min += '<option value="' + i + '">' + " 0" + i + " " + '</option>';
}
}
else {
if (MMEdit != "" && MMEdit == i) {
Min += '<option value="' + i + '" selected="selected">' + " " + i + " " + '</option>';
}
else {
Min += '<option value="' + i + '">' + " " + i + " " + '</option>';
}
}
}
//$('#Item').append(option);
}
window.onload = RecreateDynamicTextboxes;
</script>
Code for date month year validation using javascript
var fdate = document.getElementById('<%=txtFromDate.ClientID%>').value;
var tdate = document.getElementById('<%=txtToDate.ClientID%>').value;
var fromdate = fdate.split('/');
var fmonth = fromdate[0];
var fdate = fromdate[1];
var fyear = fromdate[2];
if (fmonth > 12) {
message += "From Month Should Be Less Than 12." + "\n";
}
if (fdate > 31) {
message += "From Date Cannot Be Greater Than 31." + "\n";
}
if (fyear < 2000 || fyear > 2030) {
message += "From Year Should Be In Between 2000 to 2030." + "\n";
}
var todate = tdate.split('/');
var tmonth = todate[0];
var tdate = todate[1];
var tyear = todate[2];
if (tmonth > 12) {
message += "To Month Should Be Less Than 12." + "\n";
}
if (tdate > 31) {
message += "To Date Cannot Be Greater Than 31." + "\n";
}
if (tyear < 2000 || tyear > 2030) {
message += "To Year Should Be In Between 2000 to 2030."+"\n";
}
if (message != "") {
alert(message);
return false;
}
From Date: <asp:TextBox ID="txtFromDate" Width="113px" runat="server" placeholder="mm/dd/yyyy" onkeypress="return IsValidData(event);" ondrop="return false;"
onpaste="return false;" onkeyup="this.value=this.value.replace(/^(\d\d)(\d)$/g,'$1/$2').replace(/^(\d\d\/\d\d)(\d+)$/g,'$1/$2').replace(/[^\d\/]/g,'')"></asp:TextBox> <span id="error" style="color: Red; display: none">* Invalid Character</span>
To Date: <asp:TextBox ID="txtToDate" Width="113px" runat="server" placeholder="mm/dd/yyyy" onkeypress="return IsValidData(event);" ondrop="return false;"
onpaste="return false;" onkeyup="this.value=this.value.replace(/^(\d\d)(\d)$/g,'$1/$2').replace(/^(\d\d\/\d\d)(\d+)$/g,'$1/$2').replace(/[^\d\/]/g,'')"></asp:TextBox><span id="Span1" style="color: Red; display: none">* Invalid Character</span>
I don't see that you've actually defined your IsValidData function. I'm assuming that you've done that somewhere...
You can pass this to your IsValidData function as a parameter to work with the element that triggered the event in your function..
Also you should try moving away from inline functions to event listeners. This stack post (JavaScript click event listener on class) talks about applying an event listener to a class of DOM elements.
If you are using jQuery, since you included this tag, then I'd encourage you to look into the jQuery .on() function to add event handlers. It'll make everything much easier (http://api.jquery.com/on/)
If you do not know what a javascript event listener is, then start here (https://www.w3schools.com/js/js_htmldom_eventlistener.asp)
I have some divs which are generated by jquery. Inside there is showing up the price, the title and the selected option value.
I've tried a lot of things to hide each div class "result" if no option is select, but with no luck.
Is there a way to hide each div without rewriting the whole code?
JS:
function pcc_calc_forms() {
jQuery(".calcolare").each(function (e) {
var t = jQuery(this).attr("id");
var n = pcc_form_data(t);
jQuery("#" + t + "-mostra").html('<h3 class="pcc-total">Totale : ' + n[0] + "" + "€" + '</h3><div class="content">' + n[1] + '<br /><br /></div>')
})
}
function pcc_form_data(e) {
var t = new Array(0, "");
var n = new Array;
var r = new Array;
$("#" + e + " select").each(function (e) {
var title = $(this).attr("data-title");
var inside = $(this).find("option:selected").attr("data-title");
var i = $(this).find("option:selected").html();
if (inside === undefined) {
inside = " ( " + i + " ) "
} else {
inside = " ( " + inside + " ) "
}
var i = $(this).find("option:selected").attr("data-price");
var s = parseFloat($(this).attr("data-mult"));
if (isNaN(s)) {
s = 1
}
var o = parseFloat($(this).find("option:selected").text());
if (isNaN(o)) {
o = 0
}
if (i !== undefined) {
if (i == "this") {
i = o
} else {
i = parseFloat(i)
}
t[0] = t[0] + parseFloat(i) * s;
if (s == 1) {
t[1] = t[1] + "<div class=\"result\"><b>" + title + "" + inside + "</b> : " + parseFloat(i) + "" + " € " + "</div>"
} else {
t[1] = t[1] + "<div class=\"result\"><b>" + title + "" + inside + "</b> : " + parseFloat(i) + " X " + s + " = " + parseFloat(i) * s + "" + " € " + "</div>"
}
}
});
n = [];
r = [];
return t
}
$(document).ready(function () {
pcc_calc_forms();
$(document).on("change", ".calcolare select", function () {
pcc_calc_forms()
});
});
THIS is the link to the fiddle
Thanks in advance for any hint.
$(document).on("change", ".calcolare select", function () {
var i = $(this).find('option:selected').index();
alert(i);
//if(i>0) ppc_calc_forms();
//else $('.results').hide();
})
This will find the index of the selected option... as you can see, it works, just not with your function...
I would simplify that script as much as possible..
I understand not wanting to rewrite the code substantially at this point. However, for comparison, here is the way I would do it while still holding to your general pattern:
function pcc_calc_forms() {
jQuery(".calcolare").each(function (e) {
var t = jQuery(this).attr("id");
var items = pcc_item_data(t);
var totalPrice = $.makeArray(items).reduce(function(total,item,i,a) {
return total+item.price;
},0);
text = '<h3 class="pcc-total">Totale : ' + totalPrice + "" + "€" + '</h3>';
text += '</h3><div class="content">';
items.each(function(i,item) {
if (item.mult > 1)
text += "<div class=\"result\"><b>" + item.title + " ( " + item.name + " )</b> : " + item.price + " X " + item.mult + " = " + item.price * item.mult + "" + " € " + "</div>";
else
text += "<div class=\"result\"><b>" + item.title + " ( " + item.name + " )</b> : " + item.price + "" + " € " + "</div>";
});
text += '<br /><br /></div>';
jQuery("#" + t + "-mostra").html(text);
});
}
function pcc_item_data(e) {
return $("#" + e + " select").map(function (e) {
if (this.selectedIndex > 0) {
var item = {};
item.title = $(this).attr("data-title");
var inside = $(this).find("option:selected").attr("data-title");
var i = $(this).find("option:selected").html();
item.name = inside ? inside : i;
item.price = parseFloat($(this).find("option:selected").attr("data-price"));
var mult = parseFloat($(this).attr("data-mult"));
item.mult = isNaN(mult) ? 1 : mult;
return item;
}
});
}
$(document).ready(function () {
pcc_calc_forms();
$(document).on("change", ".calcolare select", function () {
pcc_calc_forms();
});
});
What I've done:
Separate data collection (pcc_item_data) from data presentation;
this makes the code more readable and easier to maintain later.
Used map (http://api.jquery.com/jQuery.map/) and reduce (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce) to transform / aggregate arrays; they're concise
and expressive once you're familiar with them.
I'm trying to show div#options_holder and create some elements inside it by using this code:
var counter = 1;
$('#choices').on("change", ":checkbox", function(e) {
var theName = $(this).attr('name');
var theID = $(this).attr('id');
var isChecked = $(this).prop("checked");
var input, button, append = "";
$("#options_holder").show();
input = capitalize(theName) + '<input name="input_' + theName + '[]" id="' + theID + '" value="" placeholder="' + capitalize(theName) + '" />';
button = '<button type="button" class="add-size">Nuevo ' + capitalize(theName) + '</button>';
append = counter === 1 ? input += button : input;
$("#options_holder").append(append);
counter++;
console.log("You changed " + theName + ", with an id of " + theID + ", its checked property is: " + isChecked);
});
But it does not work since div#options_holder remains hidden and elements aren't created, is something wrong? It's supposed that those should happen any time I mark a checkbox, if I unmark in the other hand the process should be reverted meanind div#options_holder will be hidden and any element inside it should be destroyed, what's wrong?
Making sure that your selectors work and your IDs are correct are often easily overlooked. Glad we could help you find your typing mistake :-)
Working code fiddle: http://jsfiddle.net/pXJpr/
HTML:
<div id="choices">
<input type="checkbox" name="testName" id="testId" />
</div>
<div id="options_holder" style="display:none;">
</div>
JS:
var counter = 1;
$('#choices').on("change", ":checkbox", function(e) {
var theName = $(this).attr('name');
var theID = $(this).attr('id');
var isChecked = $(this).prop("checked");
var input, button, append = "";
$("#options_holder").show();
input = capitalize(theName) + '<input name="input_' + theName + '[]" id="' + theID + '" value="" placeholder="' + capitalize(theName) + '" />';
button = '<button type="button" class="add-size">Nuevo ' + capitalize(theName) + '</button>';
append = counter === 1 ? input += button : input;
$("#options_holder").append(append);
counter++;
console.log("You changed " + theName + ", with an id of " + theID + ", its checked property is: " + isChecked);
});
function capitalize(s) {
return s;
}