How to replace text on an click event using jquery - javascript

Here when i click on a particular player its score is displayed.But when again a player is clicked the previous score doesn't get cleared.So pls can anyone provide the solution.
$(document).ready(function () {
for (var i = 0; i < temp.length; i++)
$("#sidebar").append("<div id=" + i + " class='player'>" + temp[i].name + "</div>")
$(".player").click(function () {
var pla = $(this).attr('id');
$("#score").append(temp[pla].score);
//$(".content").append(a[pla].Events);
var selected = $(this).hasClass("highlight");
var a = $("span").append($(this).text());
$(".player").removeClass("highlight");
if (!selected) {
$(this).addClass("highlight");
$(this.Text()).remove();
}
});
});

You might need to add a call to .html() for the sidebar to clear its content, add it at the top of your document ready function.
So something like:
$("#sidebar").html();

Related

dynamic list in javascript how to call function from specific <li>

I get the message list from the API and create a dynamic array using javascript. I would like a new page with message details to be started when a specific row is pressed.
How do I implement a call to showMessage () on a specific table row?
var list = document.getElementById("listOfMessage");
init();
function init() {
for (var i = 0; i < messageList.length; i++) {
var message = messageList[i];
var li = document.createElement("li");
var a = document.createElement("a");
var text = document.createTextNode("Nadawca: " + message.fullName);
a.appendChild(text);
a.setAttribute('onclick', showMessage(message));
list.appendChild(li);
//list.innerHTML += "<li><a href="showMessage(message)"><h2>Nadawca: " + message.fullName + "
//</h2></a></li>";
}
//list = document.getElementById("listOfTask");
}
function showMessage(message) {
window.sessionStorage.setItem("message", JSON.stringify(message));
window.location.href = 'message.html';
}
In the code above, the showMessage () function is immediately called when the array is initialized. How to make it run only after clicking on a row?
I could add an id attribute to the (a) or (li) element in the init () function, but how to find it later and use it in this code:
var a = document.getElementById('1');
a.addEventListener('click', function() {
window.sessionStorage.setItem("message", JSON.stringify(messageList[0]));
window.location.href = 'message.html';
});
I found a way to solve this problem.
Using this code fragment, we can call a function for a specific element in a dynamically created list.
function init() {
for (var i = 0; i < messageList.length; i++) {
var message = messageList[i];
list.innerHTML += "<li id="+i+"><a onClick="+
"><h2>Nadawca: " + message.fullName + "</h2></a></li>";
}
//$(document).on("click", "ui-content", function(){ alert("hi"); });
$(document).ready(function() {
$(document).on('click', 'ul>li', function() {
var idName = $(this).attr('id');
showMessage(messageList[idName]);
});
});
}

How to find visible child in hidden parent

I want to show a div which has the error message span visible in it. I tried the following codes but it works only when the container is visible otherwise it is unable to find in it.
Can someone share the reason and solution to it?
Code 1:
Using .length
$(".has-warning:visible").each(function() {
var id = this.id;
var divs = ["wReq_div", "mcatIsq_div", "glDetail_div"];
for (var i = 0; i < divs.length; i++) {
if ($("#" + divs[i] + " #" + id).length) {
console.log("found in " + divs[i]);
return false;
}
}
});
This gives true for the container if it's visible otherwise not.
Code 2:
Using $.contains
$(".has-warning:visible").each(function(){
var id = this.id;
var divs = ["wReq_div","mcatIsq_div","glDetail_div"];
for(var i=0;i<divs.length;i++){
if($.contains($("#"+divs[i])[0],$("#"+id)[0])){
console.log("found in " + divs[i]);
return false;
}
}
});
It's also working only if the container is visible.
So my main problem is:
Parent is hidden and child has display not none, how to find that shown child in the hidden parent
To find that which parent div(hidden) has an error div with given id so that I can show that parent div.
Here is the CodePen
I don't want to use the method of changing class from a hidden one to visible one to display my errorMsg as I'll have to do a lot of changes in multiple files.
From the docs
jQuery( ":visible" )
Elements are considered visible if they consume space in the document. Visible elements have a width or height that is greater than zero.
If a parent is hidden, all it's children will also be hidden. So, $(".has-warning:visible") will not return the child elements, even if they're not hidden.
you need to rely on the display property of the child elements, rather than the :visible attribute and try something like this,
function checkMsg1(){
$(".has-warning").each(function() {
var id = this.id;
var i=0;
var divs = ["wReq_div", "mcatIsq_div", "glDetail_div"];
for (i = 0; i < divs.length; i++) {
if ($("#" + divs[i] +" #"+id).css("display") !== 'none') {
$("#" + divs[i]).show();
}
}
});
}
I used following code to overcome this problem, Please suggest if you have better one:
var divs = ["wReq_div","mcatIsq_div","glDetail_div"];
$(".has-warning").each(function(){
if($(this).css("display") != "none"){
var id = this.id;
for(var i=0;i<divs.length;i++){
if($.contains($("#"+divs[i])[0],$("#"+id)[0])){
console.log("found in " + divs[i]);
break;
}
}
}
});
But it first selects all the divs and may increase time.
you will not find .has-warning:visible as its parent is not visible. But you can check for parent div if it is hidden or not.
$(".has-warning").each(function() {
if($(this).css("display") != "none"){
var id = this.id;
var i=0;
var divs = ["wReq_div:hidden", "mcatIsq_div:hidden", "glDetail_div:hidden"];
for (i = 0; i < divs.length; i++) {
if ($("#" + divs[i] + " #" + id).length) {
alert("found in " + divs[i] + " " + id);
// Add code to display that div
}
else {
alert("not found in " + divs[i]+ " " + id);
}
}
}
});

Dynamic generation of select clear other elements in javascript

I have a for loop that creates as many as I write in an input field. first time I write a number in the imput all is ok... he generates for example 3 fields. When I delete 3 and write 5, he add two objects but he also clear other... if I select an option in the first , I want to keep it selected when I add some other fields....
this is an example: https://jsfiddle.net/exv8s2sq
and this is the code:
Insert number<input type="text" id="number" name="number" ><br><br>
<div id="container"></div>
<script>$('#number').on('keyup', function () {
changenumber(this.value);
});
$('#number').on('paste', function () {
changenumber(this.value);
});
var now = 0;
function changenumber(val) {
container = document.getElementById("container");
var diff = val - now;
if (diff > 0) {
for (var u = now + 1; u <= val; u++) {
container.innerHTML = container.innerHTML +
" Select from options <select id='selectobj" + u + "' name='selectobj" + u + "' style='width:25%;'>" +
"<option>A</option>" +
"<option>B</option>" +
"<option>C</option>" +
"</select><br><br>";
now = u;
}
}
}</script>
thanks
Lorenzo from Rome
Instead of using innerHTML, i would suggest using jQuery as selector and use element.append(selectbox) to add new items. I've updated your fiddle with a working example based on your code:
http://jsfiddle.net/exv8s2sq/1/
There is also room to refactor your code a bit. When using jQuery, native javascript isn't really necessary for dom manipulation.
Wrap your elements in a div with a specific class so you can easily count how many items you already have. Then depending on the number you enter, check whether you need to add or remove elements from your container.
Use jQuery selectors all the way, it is easier to identify your elements, and use the methods it provides such as .each() and .append()
$('#number').on('input', function () {
changenumber(this.value);
});
function changenumber(val) {
if (val !== '') {
// Wrap your elements in a div with a specific class
var select = '<div class="select-wrapper">Select from options <select><option>A</option><option>B</option><option>C</option></select></div>';
// Count number of selects div
var nbOfSelects = $('.select-wrapper').length;
// Check if you need to add or remove elements
if (nbOfSelects < val) {
// Add an element
for (var i = 0; i < (val - nbOfSelects); i++) {
$('#container').append(select);
}
} else {
// Loop through elements
$('.select-wrapper').each(function (i) {
// Remove an element
if (i >= val) {
$(this).remove();
}
});
}
}
}
JSFiddle demo
Try this, it adds an attribute of selected to the previous selected option using an onchange event listener
$('#number').on('keyup', function () {
changenumber(this.value);
});
$('#number').on('paste', function () {
changenumber(this.value);
});
var now = 0;
function changenumber(val) {
container = document.getElementById("container");
var diff = val - now;
if (diff > 0) {
for (var u = now + 1; u <= val; u++) {
container.innerHTML = container.innerHTML +
" Select from options <select onchange='updateDom(this)' id='selectobj" + u + "' name='selectobj" + u + "' style='width:25%;'>" +
"<option>A</option>" +
"<option>B</option>" +
"<option>C</option>" +
"</select><br><br>"; now = u;
}
}
}
function updateDom(s){
s.options[s.selectedIndex].setAttribute("selected","selected")
}

Simplifying some jQuery code of keyup inputs

Thing that I'm making
I am making a webpage, which is to generate forum code automatically
when I enter content into inputs. Each character will be in different colors and the sentence will look like a gradient.
This is the jsfiddle sample.
When I enter a-p-p-l-e in to those inputs, the result will be as follow:
[color=3173d8]a[/color][color=416cd9]p[/color][color=5e5bdb]p[/color][color=8248dd]l[/color][color=a335df]e[/color]
Question
When more and more inputs and spans are created, the js code will be so bulky. But I don't know how to simplify them. I have tried to use thing like $(this).attr('target') , it just doesn't work. Can anyone help me to make it shorter if I would like to add more inputs, like saying 30.
More
What if i want the focus move itself to the next input if that input is typed with character already? Then I will be able to type word with 'tab'.
You can simplify your code like this.
Bind the keyup event once by using the id starts with selector.
var colors = ["3173d8", "416cd9", "5e5bdb", "8248dd", "a335df"]
$("[id^=input]").each(function (i) {
$(this).css('background', '#' + colors[i]);
});
$("[id^=input]").keyup(function () {
var index = $("[id^=input]").index(this);
$("span[id^=span]").eq(index).html('[color=' + colors[index] + ']' + $(this).val() + '[/color]');
});
Note that $("[id^='input']") will return all the elements whose id starts with "input".
Demo Fiddle
Edit for changing the focus
var colors = ["3173d8", "416cd9", "5e5bdb", "8248dd", "a335df"]
$("[id^=input]").each(function(i) {
$(this).css('background', '#' + colors[i]);
});
$("[id^=input]").keyup(function() {
if ($(this).val().trim().length) {
$(this).next().focus();
}
var index = $(this).index();
$("span[id^=span]").eq(index).html('[color=' + colors[index] + ']' + $(this).val() + '[/color]');
});
Edited Fiddle
Automatic making input, and full js solution. And it's easy to add new color.
// Define color separately
var colors = [
"3173d8", "416cd9", "5e5bdb", "8248dd", "a335df"
];
(function() {
$("body")
.append('<div id="parent"></div>')
.append('<code id="output"></code>');
var f = function() {
$("#output").html("");
for (var i = 0, val = ""; i < colors.length; i++) {
val = $("#parent input[data-num=" + i + "]").val();
$("#output").append('[color=' + colors[i] + ']' + val + '[/color]');
//or $("#output").append('<span id="span'+i+'">'+c+'</span>');
}
};
for (var i = 0; i < colors.length; i++) {
$('<input size="4" maxlength="1" />')
.attr("data-num", i)
.css('background', '#' + colors[i])
.keyup(f)
.appendTo("#parent");
}
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

JQuery button.click() handler fires without click

Right now I'm doing some clean up code for my auction game, but my function is fired immediately after endAuction() is called rather than when the button is clicked. I can't seem to figure out why, and I'm not terribly familiar with JavaScript or jQuery, can anyone point out my issue?
endAuction:function()
{
var i = 0;
var btnID = "as" + (i).toString(),
liID = "asli" + (i).toString();
var cleanBtn = $('li#' + liID + ' button#' + btnID);
cleanBtn.text("Sold!");
var btn = $('#' + btnID);
btn.off().click(this.cleanUpAuction());
},
cleanUpAuction:function()
{
console.log("Removing button");
userStats.money += currentBid;
currentBid = 0;
var i = 0;
var liID = "asli" + (i).toString();
var carElement = $('li#' + liID);
carElement.remove();
},
You are calling the function, not assigning a reference to it.
Change
.click(this.cleanUpAuction())
to
.click(this.cleanUpAuction)
or
.click($.proxy(this.cleanUpAuction, this))

Categories

Resources