Field updates for a second then disapears - javascript

so i made a field status as p paragraph, and it supposed to be able to hold a value after button click but it only appears momentary and disappears
the library js just has the array required to fill in the data needed
<script src="library.js"></script>
<b id="chakra"></b>
<div id="planet"></div>
<script>
var index = setChakra(0);
var planetConection = "";
function setChakra(index){
document.getElementById("chakra").innerHTML = chakra[index];
while (index < chakra.length){
getPlanets(index);
if (index < chakra.length-1) index++;
else index = 0;
break;
}
return index;
}
function getPlanets(chakra){
var planetIndex = 0;
document.getElementById("planet").innerHTML = "";
while( planetIndex < chakraPlanets[chakra].length){
document.getElementById("planet").innerHTML = document.getElementById("planet").innerHTML + planetDesc[chakraPlanets[chakra][planetIndex]] +
"<form>" +
"<input id=\"planetStatus" + planetIndex + "\" type=\"text\" name=\"plntStat\">" +
"<button onclick=\"getPlanetConection(" + planetIndex + ")\">Click Me!</button>" +
"</form>" +
"<p id=\"status\"></p>";
planetIndex++;
}
}
function getPlanetConection(planetIndex){
planetConection = document.getElementById("planetStatus" + planetIndex).value;
document.getElementById("status").innerHTML = planetConection;
}
</script>
<button onclick = "index = setChakra(index)" >Click Me!</button>

Ok solved it button is meant to be input if i am not refreshing the page
<script src="library.js"></script>
<b id="chakra"></b>
<div id="planet"></div>
<script>
var index = setChakra(0);
var planetConection = "";
function setChakra(index){
document.getElementById("chakra").innerHTML = chakra[index];
while (index < chakra.length){
getPlanets(index);
if (index < chakra.length-1) index++;
else index = 0;
break;
}
return index;
}
function getPlanets(chakra){
var planetIndex = 0;
document.getElementById("planet").innerHTML = "";
while( planetIndex < chakraPlanets[chakra].length){
document.getElementById("planet").innerHTML = document.getElementById("planet").innerHTML + planetDesc[chakraPlanets[chakra][planetIndex]] +
"<form>" +
"<input id=\"planetStatus" + planetIndex + "\" type=\"text\" name=\"plntStat\">" +
"<input value=\"Click\" type=\"button\" onclick=\"getPlanetConection(" + planetIndex + ")\"/>" +
"</form>" +
"<p id=\"status" + planetIndex + "\"></p>";
planetIndex++;
}
}
function getPlanetConection(planetIndex){
planetConection = document.getElementById("planetStatus" + planetIndex).value;
document.getElementById("status" + planetIndex).innerHTML = planetConection;
}
</script>
<button onclick = "index = setChakra(index)" >Click Me!</button>

I think the page is reloading. Add a type attribute with value 'button' to your button.
Like so:
<button type="button" onclick = "index = setChakra(index)" >Click Me!</button>
"<button type=\"button\" onclick=\"getPlanetConection(" + planetIndex + ")\">Click Me!</button>"
This is so that the button acts as a button and not a submit button.

Related

Trying to get the HTML displayed to change every time a new button is clicked with jquery

let table = 6;
let i = 1;
$(function() {
let $newOperatorButton = $('button');
$newOperatorButton.on('click', function math(){
let msgOperator = '';
let expression;
let operator = $(this).attr("value");
if(operator === '+'){
msgOperator = ' + ';
expression = (table + i);
while(i < 11){
msg += table + msgOperator + i + ' = ' + (table + i) + '<br />';
i++;
}
} else if (operator === '-') {
msgOperator = ' - ';
expression = (table - i);
while(i < 11){
msg += table + msgOperator + i + ' = ' + (table - i) + '<br />';
i++;
}
some code missing but it adds multiplication and division
let el = document.getElementById('blackboard');
el.innerHTML = msg;
}
);
});
This code is inside the body tag in my index.html
<section id="page">
<section id="blackboard"></section>
</section>
<form id="operator">
<button name="add" type="button" value="+">+</button>
<button name="subtract" type="button" value="-">-</button>
<button name="multiply" type="button" value="x">x</button>
<button name="division" type="button" value="/">/</button>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="/index.js"></script>
I have it so it prints out a table with 10 numbers depending on the button clicked. For ex. table = 6 and i = 1 is 6+1=7.... 6+10=16
You need an if statement at the end that reset your equations and variables.
after you've run your equation "i" is still equal to 11 so it never passes into the while loops again, you also need to empty your message so it doesn't keep adding addition text to your existing text.
$("#blackboard").html(msg)
if (i == 11) {
i = 1
msg = ""
}

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!

Javascript wrong variable type

Hello I'm preparing little guessing word game.
Somehow the type of my variable get changed from string to obj type what causes an Uncaught TypeError.
Here is a fragment of code:
let passwordArray = ["Java Script Developer", "FrontEnd"];
let sample = passwordArray[Math.floor((Math.random() *
passwordArray.length))];
let password = sample.toUpperCase();
let new_password = "";
for(let x =0; x<password.length;x++){
if(password[x]===" "){new_password += " "}
else{new_password += "-"}
}
$("#password span").text(new_password);
This part works correclty problem appears when I want to repalce a letter
String.prototype.replaceAt = function(index, replacement){
return this.substr(0,index) + replacement + this.substr(index + replacement.length)
};
function check(num) {
let test = false;
let temp = $(event.target).val();
if(password.indexOf(temp)>-1){test=true; /*alert(test +"/"+temp+"/"+password)*/}
$("#"+num).attr("disabled", true);
if(test === true) {
$("#"+num).removeClass("letter").addClass("hitletter");
let indeksy =[];
for(let i =0; i<password.length;i++ ){
if(password.charAt(i) === temp){indeksy.push(i)}
}
for(let x=0; x<indeksy.length;x++) {
let indx = indeksy[x];
new_password = new_password.replaceAt(indx, temp);
}
$("#password").html(new_password);
}};
My HTML basically is just:
<nav>
<input type="button" value="o mnie" id="me">
<input type="button" value="kalkulator" id="cal">
<input type="button" value="Wisielec" id="wis">
<input type="button" value="Memory" id="mem">
</nav>
<div id="content"></div>
Rest is dynamically added in JS:
$(function() {
$("#wis").click(function () {
$("#content").empty().append("" +
"<div id='container'>\n" +
"<div id='password'><span>Sample text</span></span></div>\n" +
"<div id='counter'>Counter: <span id='result'></span></div>\n" +
"<div id='gibbet' class='image'></div>\n" +
"<div id='alphabet'></div>\n" +
"<div id='new'>\n" +
"<input type='text' id='new_password'/>\n" +
"<button id='add' onclick='newPass()'>Submit</button>\n" +
"</div>\n" +
"</div>"
);
start();
});
});
function start(){
let new_password = "";
$("#contetn").empty();
let letters = "";
for(let i=0; i<32; i++){
letters += "<input class='letter' type='button' value='"+litery[i]+"' onclick='check("+i+")' id='"+i+"'/>"
}
$("#alphabet").html(letters);
$("#result").text(mistakeCounter);
for(let x =0; x<password.length;x++){
if(password[x]===" "){new_password += " "}
else{new_password += "-"}
}
$("#password span").text(new_password);
}
The problem is that variable new_password is somehow changing from type string to type object when i want to use function replaceAt()
looking at your code, with the new String.prototype.replaceAt this error can happen on 2 situations:
when the variable that uses replaceAt is not a string, example:
null.replaceAt(someIndex,'someText');
{}.replaceAt(someIndex,'someText');
[].replaceAt(someIndex,'someText');
the other situation is when you pass null or undefined as replacement:
"".replaceAt(someIndex,undefined);
"".replaceAt(someIndex,null);
just add some verification code and should be working good

Looping through text boxes, using id as a variable?

Basically I'm trying to populate an array with some values in text boxes. I thought I could do it by incrementing though ids, but it isn't working.
Here it is:
var sections = 0;
var mod = [];
var identifier = 0;
function addSection(){
sections++;
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'> <br>";
}
function removeSection(){
if (sections > 0){
sections--;
identifier -= 3;
document.getElementById("input").innerHTML = "";
for(i=0; i<sections; i++){
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'> <br>";
}
}
}
function calculate(){
populateArray();
}
function populateArray(){
var i,j;
for(i=0;i<sections * 3;i++){
var pop = i.toString();
mod[i] = parseInt(document.getElementById(pop).innerHTML.value);
i++;
pop = i.toString();
mod[i] = parseInt(document.getElementById(pop).innerHTML.value);
i++
pop = i.toString();
mod[i] = parseInt(document.getElementById(pop).innerHTML.value);
}
document.getElementById("debug").innerHTML = mod.toString();
}
<!doctype html>
<html>
<head>
<title>To Pass v1.0</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<h1>TO PASS</h1>
<button onclick="addSection()">Add Section</button>
<button onclick="removeSection()">Remove Section</button>
<div id='input'></div>
<button onclick="calculate()">Calculate</button>
<div id='output'></div>
<div id='debug'></div>
</body>
<script type="text/javascript" src="js/main.js"></script>
</html>
Is it possible doing it my method, or will it inevitably not work for whatever reason? Doing some searches it seems jquery might be the way to go, but I'm not sure how to get started with that.
jQuery certainly simplifies things, but it can't do anything that JavaScript can't do, and many amazing websites were built long before jQuery came into existence.
In populateArray(), remove innerHTML here:
mod[i] = parseInt(document.getElementById(pop).innerHTML.value);
Should be:
mod[i] = parseInt(document.getElementById(pop).value);
You can simplify the function like this:
function populateArray() {
var i;
for(i = 0 ; i < sections * 3 ; i++) {
mod[i] = parseInt(document.getElementById(i).value);
}
document.getElementById('debug').innerHTML = mod.toString();
}
In addSection(), this wipes out the values of existing input elements:
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
Instead, you should create new input elements and append them.
Here's a rewrite of the function:
var input= document.getElementById('input');
function addSection(){
var inp, i;
sections++;
for(var i = 0 ; i < 3 ; i++) {
inp= document.createElement('input');
inp.type= 'text';
inp.id= identifier++;
input.appendChild(inp);
}
input.appendChild(document.createElement('br'));
} //addSection
In removeSection(), values of all input elements are wiped out.
Instead of rewriting that function, I've done a complete rewrite or your program, without any global variables and without assigning IDs to the input elements.
If you have any questions, I'll update my answer with explanations.
Snippet
function addSection() {
var input= document.getElementById('input'),
sect= document.querySelector('section');
input.appendChild(sect.cloneNode(true));
}
function removeSection() {
var input= document.getElementById('input'),
sects= document.querySelectorAll('section');
if(sects.length > 1) {
input.removeChild(sects[sects.length-1]);
}
}
function calculate() {
var inp= document.querySelectorAll('section input'),
debug= document.getElementById('debug'),
mod= [],
i,
val;
for(i = 3 ; i < inp.length ; i++) {
val= parseInt(inp[i].value);
mod.push(val || 0);
}
debug.innerHTML = mod.toString();
}
section:first-of-type {
display: none;
}
<button onclick="addSection()">Add Section</button>
<button onclick="removeSection()">Remove Section</button>
<div id='input'>
<section>
<input type="text">
<input type="text">
<input type="text">
</section>
</div>
<button onclick="calculate()">Calculate</button>
<div id='output'></div>
<div id='debug'></div>
This version of your script stores the actual elements in an array of sections. That way you can loop through them as you would an array, and alter the contents that way.
Here's a pen of the code: looping through added elements
var sections = [];
var output = document.getElementById('input');
function addSection(){
var section = document.createElement('div');
for (var i = 0; i < 3; i++) {
el = document.createElement('input');
el.type = 'text';
section.appendChild(el);
}
sections.push(section);
output.appendChild(section);
}
function removeSection(){
if (sections.length > 0){
output.removeChild(sections.pop())
}
}
function calculate(){
populateArray();
}
function populateArray(){
for (var i = 0; i < sections.length; i++) {
for (var j = 0; j < sections[i].children.length; j++ ) {
sections[i].children[j].value = (i+1) * (j+2);
}
}
}
If your problem is the NaN, this is because you select an input field and then first try to read its innerHtml before reading its value. Read values of inputs directly.
var sections = 0;
var mod = [];
var identifier = 0;
function addSection(){
sections++;
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'> <br>";
}
function removeSection(){
if (sections > 0){
sections--;
identifier -= 3;
document.getElementById("input").innerHTML = "";
for(i=0; i<sections; i++){
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'> <br>";
}
}
}
function calculate(){
populateArray();
}
function populateArray(){
var i,j;
for(i=0;i<sections * 3;i++){
var pop = i.toString();
mod[i] = parseInt(document.getElementById(pop).value);
i++;
pop = i.toString();
mod[i] = parseInt(document.getElementById(pop).value);
i++
pop = i.toString();
mod[i] = parseInt(document.getElementById(pop).value);
}
document.getElementById("debug").innerHTML = mod.toString();
}
<!doctype html>
<html>
<head>
<title>To Pass v1.0</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<h1>TO PASS</h1>
<button onclick="addSection()">Add Section</button>
<button onclick="removeSection()">Remove Section</button>
<div id='input'></div>
<button onclick="calculate()">Calculate</button>
<div id='output'></div>
<div id='debug'></div>
</body>
<script type="text/javascript" src="js/main.js"></script>
</html>

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