Div contents disappears about milliseconds of appearing - javascript

HTML:
<form id='pool_play'>
<?php
$PLAYERS = 8;
for ($i=1; $i <= $PLAYERS; $i++) {
print $i . ' <input type="text" class="initial_players" autofocus> <br/>';
}
?>
<br>
<button type="submit" class="random"> Randomize bracket</button>
</form>
<p class="debug"></p>
js:
$("#pool_play").submit(function(event) {
var participants = $('.initial_players').map(function() {
return $(this).val();
}).get();
for (var i = 0; i < participants.length; i++) {
$('p.debug').append(participants[i] + " ");
}
});
I'm basically trying to do is that when the form of #pool_play is submitted, print the contents of the input boxes in the .debug paragraph tag.
What happens is that it appears for a few milliseconds and then disappears. My guess is when the page is submitted, the old data(meaning the content of the .debug paragraph after it gets filled) gets thrown away. Tips?

You need to prevent the submit action or the page will just reload without your changes to the page.
$("#pool_play").submit(function(event) {
var participants = $('.initial_players').map(function() {
return $(this).val();
}).get();
for (var i = 0; i < participants.length; i++) {
$('p.debug').append(participants[i] + " ");
}
event.preventDefault();
return false;
});
It may be a better idea however to change your button to a button instead of a submit
<button type="button" class="random"> Randomize bracket</button>

You can prevent the page from submitting using event.preventDefault()
$("#pool_play").submit(function(event) {
var participants = $('.initial_players').map(function() {
return $(this).val();
}).get();
for (var i = 0; i < participants.length; i++) {
$('p.debug').append(participants[i] + " ");
}
event.preventDefault();//stops submit
});

Look at code. You catching submit event, getting data printing them... And then you go out from your function, so default action for submit event are executed by browser, because you don't stop it. Thats why you see this content only in miliseconds - browser is refreshing page.
You should use event.preventDefault() function to prevent browser from submiting form after execution your function.

Related

alert message in jQuery causing the jQuery code to run again and again

The following code is used to avoid duplicates input fields in HTML form
$(document).ready(function() {
$(".classesName").submit(function(e) {
e.preventDefault();
var frm = document.querySelector('form.classesName');
frm.addEventListener('submit', function(e) {
e.preventDefault();
var classArr = [];
console.log("HI"); // To show that ajax is called again and again
var inputs = frm.querySelectorAll('input[type=text]');
inputs = Array.from(inputs); // So as to avoid UPPERCASE and lowercase i.e, HEL and hel
for (var i = 0; i < inputs.length; i++) {
inputs[i] = inputs[i].value.toUpperCase();
console.log(inputs[i]);
if (classArr.indexOf(inputs[i].value) != -1) {
alert("Duplicate Name Found");
return false;
} else
classArr.push(inputs[i].value);
}
frm.submit();
});
});
});
The problem is that when i enter HELLO and hello in the HTML form an alert message occurs saying the error, when i click ok and then edit to say HELLO and NEW.
#PROBLEM : the ajax call starts again, so now the alert message occurs twice when there is no duplicate values.
F12 BROWSER OUTPUT
HI
2HELLO
HI
HELLO
NEW
HI
HELLO
NEW
The problem is that you're creating multiple event listeners. $(".classesName").submit() creates a jQuery listener. When you call that it creates a regular JavaScript listener with frm.addEventListener(). The next time you submit, it runs both event listeners, and also adds another event listener.
You don't need to add the listener multiple times. Just use the jQuery listener.
Another problem is that you're replacing inputs[i] with its uppercase value, but then you're using inputs[i].value when searching classArr. Since inputs[i] is now a string, it doesn't have a .value property. Instead of replacing the array element, use a new variable.
$(document).ready(function() {
$(".classesName").submit(function(e) {
e.preventDefault();
var classArr = [];
console.log("HI"); // To show that ajax is called again and again
var inputs = $(this).find('input[type=text]');
for (var i = 0; i < inputs.length; i++) {
var val = inputs[i].value.toUpperCase();
console.log(val);
if (classArr.indexOf(val) != -1) {
alert("Duplicate Name Found");
return false;
} else
classArr.push(val);
}
this.submit();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="classesName">
<input type="text"><br>
<input type="text"><br>
<input type="text"><br>
<input type="text"><br>
<input type="text"><br>
<input type="text"><br>
<input type="submit">
</form>

How can I make the options appear in a select dynamically?

I am trying to load the following options in my html, generated in javascript.
HTML:
<button type="submit" onClick="input(data)">Add</button>
<select id="processSelect" name="process">
</select>
Javascript:
function input(input){
//my code
createOptionsSelectProcess(arrayResponse);
}
function createOptionsSelectProcess(arrayResponse){
var html = '';
var arrayLength = arrayResponse.length;
for (var i = 0; i < arrayLength; i++) {
html += '<option value="'+ arrayResponse[i] +'">' + arrayResponse[i]
+ '</option>';
}
document.getElementById("processSelect").innerHTML = html;
}
However, the result I have observed in debug is that the options are generated in the select, but they disappear when the execution is finished. Does anyone know what the reason may be?
button type submit will submit the form and refresh the page, use
<button type="button" onClick="input(data)">Add</button>
Also by default button is of type submit so if you don't put it it will still submit the form.
You don't need the function input(input). You can use the event listener submit to submit the form.
document.addEventListener('submit', () => createOptionsSelectProcess(data))
function createOptionsSelectProcess(arrayResponse) {
var html = '';
var arrayLength = arrayResponse.length;
for (var i = 0; i < arrayLength; i++) {
html += '<option value="'+ arrayResponse[i] +'">' + arrayResponse[i] + '</option>';
}
document.getElementById("processSelect").innerHTML = html;
}
<form>
<button>Add</button>
<select id="processSelect" name="process"></select>
</form>
You could use <button>Add</button> or <input type="submit" value="Add">. They will both submit the form without an onClick attribute.

How to enable actions on toggle selected items

I'm developing an Admin Panel on a website (Python + Flask) and I came across with an issue while trying to implement a Select All toggle.
The table looks like the following:
The toggle itself has been implemented but now I want to make it useful.
Upon clicking the 'SELECTED' button I want to be able to delete each and every selected item (flag) but I'm not exacly sure how I can pull it off.
Each flag can be individually deleted by clicking on the glyphicon-trash according to the following Python/HTML:
<button onclick="deleteSelected('politician')">SELECTED</button>
{% for flag in flags %}
<tr>
<!-- Check box -->
<td style="width: 60px;"><input type="checkbox" name="politician" value="bar1"></td>
<!-- First Name -->
<td class="col-title">{{flag.flagtitle}}</td>
<!-- Last Name -->
<td class="col-description">{{flag.flagreason}}</td>
<!-- Details -->
<td>
<a href="/flag/{{ flag.idflag }}">
<span class="glyphicon glyphicon-info-sign"></span>
</a>
</td>
<!-- Edit icon -->
<td class="list-buttons-column">
<a href="/politician/{{ flag.politician }}">
<span class="glyphicon glyphicon-pencil"></span>
</a>
</td>
<!-- DELETE ITEM/FLAG -->
<td class="col-delete">
<form action ="/delete_flag/{{ flag.idflag }}" method="POST">
<button onclick="return confirm('Are you sure you want to delete this flag?');">
<span class="fa fa-trash glyphicon glyphicon-trash"></span>
</button>
</form>
</td>
</tr>
{% endfor %}
My idea was to develop a JavaScript function to delete the selected content but I'm not sure how I can get the flag.idFlag, which is the flags' id's associated.
I thought it would look something like this:
function deleteSelected(elem) {
checkboxes = document.getElementsByName(elem);
for(var i=0, n=checkboxes.length;i<n;i++) {
if (checkboxes[i].checked) {
delete((checkboxes[i].getSelectedFlag).idFlag)
}
}
}
Obviously the code above doesn't work, it was just meant to give you an idea of what I'm looking for.
Is there a way I can do this? Thanks in advance.
EDIT:
Ok so I figured it out. Considering I had to submit multiple forms where action="/delete_flag/flag.idFlag", I added a column to the table where the flag's id would be visible. Like the following:
For that matter, I created a JS function to retrieve the first value of each row (ID) and store it in an array of IDs so that I could create and submit a form for each one of them.
For each ID of the array I create a form where form.action = "/delete_flag/" + retrievedID. See code below.
function deleteRecords() {
var arrayOfIDs;
arrayOfIDs = $('#table-style').find('[type="checkbox"]:checked').map(function(){
return $(this).closest('tr').find('td:nth-child(2)').text();
}).get();
var delFlagForm = document.createElement("form");
var action;
var formID;
var submitFormStr;
for (var i = 0; i < arr.length; i++) {
action = "/delete_flag/" + arr[i];
formID = 'form' + i;
delFlagForm.setAttribute("id", formID);
delFlagForm.setAttribute("method", "post");
delFlagForm.setAttribute("action", action);
delFlagForm.submit();
}
}
This sounded good in my head until I realised multiple form submissions will only work asynchronously. So I made the following changes and this is where I'm stuck right now. The forms simply won't be submitted, nothing happens:
function deleteRecords() {
var arraryOfIDs;
arraryOfIDs = $('#table-style').find('[type="checkbox"]:checked').map(function(){
return $(this).closest('tr').find('td:nth-child(2)').text();
}).get();
var delFlagForm = document.createElement("form");
var action;
var formID;
var submitFormStr;
for (var i = 0; i < arr.length; i++) {
action = "/delete_flag/" + arr[i];
formID = 'form' + i;
delFlagForm.setAttribute("id", formID);
delFlagForm.setAttribute("method", "post");
delFlagForm.setAttribute("action", action);
if (i != 0) submitFormStr += ' #' + formID;
else submitFormStr = '#' + formID;
}
$('submitFormStr').submit();
return false;
}
The variable submitFormStr updated within the loop stores the id for each form created like the following: #form0 #form1so for this reason I don't understand why the piece of code $('submitFormStr').submit(); which is equivalent to $('#form0 #form1').submit(); is not working.
Is there anything I'm doing wrong?
Ok so I figured it out. Considering I had to submit multiple forms where action="/delete_flag/flag.idFlag", I added a column to the table where the flag's id would be visible. Like the following:
For that matter, I created a JS function to retrieve the first value of each row (ID) and store it in an array of IDs so that I could create and submit a form for each one of them.
For each ID of the array I create a form where form.action = "/delete_flag/" + retrievedID. See code below.
function deleteRecords() {
var arrayOfIDs;
arrayOfIDs = $('#table-style').find('[type="checkbox"]:checked').map(function(){
return $(this).closest('tr').find('td:nth-child(2)').text();
}).get();
var delFlagForm = document.createElement("form");
var action;
var formID;
var submitFormStr;
for (var i = 0; i < arr.length; i++) {
action = "/delete_flag/" + arr[i];
formID = 'form' + i;
delFlagForm.setAttribute("id", formID);
delFlagForm.setAttribute("method", "post");
delFlagForm.setAttribute("action", action);
delFlagForm.submit();
}
}
This sounded good in my head until I realised multiple form submissions will only work asynchronously. So I made the following changes and this is where I'm stuck right now. The forms simply won't be submitted, nothing happens:
function deleteRecords() {
var arraryOfIDs;
arraryOfIDs = $('#table-style').find('[type="checkbox"]:checked').map(function(){
return $(this).closest('tr').find('td:nth-child(2)').text();
}).get();
var delFlagForm = document.createElement("form");
var action;
var formID;
var submitFormStr;
for (var i = 0; i < arr.length; i++) {
action = "/delete_flag/" + arr[i];
formID = 'form' + i;
delFlagForm.setAttribute("id", formID);
delFlagForm.setAttribute("method", "post");
delFlagForm.setAttribute("action", action);
if (i != 0) submitFormStr += ' #' + formID;
else submitFormStr = '#' + formID;
}
$('submitFormStr').submit();
return false;
}
The variable submitFormStr updated within the loop stores the id for each form created like the following: #form0 #form1so for this reason I don't understand why the piece of code $('submitFormStr').submit(); which is equivalent to $('#form0 #form1').submit(); is not working.
Is there anything I'm doing wrong?

Javascript form submits to new page -- how can I keep it on the same page?

beginner programmer here. Trying to create a very primitive "chat interface", in JSP where I type in some words, they're stored in an array, then, ideally, spit back out on the same page. I've got the code somewhat working, but it loads to a new page.
I've tried a number of different things that I read on the net, including trying to add "return false" to my showChats function, trying to change the submit to a button and doing "onclick", but it's still not working, always loads a new page. Any ideas on how to solve this?
Thanks in advance. Here's the code:
<script>
counter = 0;
//Array containing initial elements.
var chats = [];
function show_array(array) {
array[counter] = document.getElementById("chatlet").value;
for (x = 0; x < array.length; x++){
document.write(array[x] + "<br/>");
}
counter++;
}
</script>
<form action="agenda2.jsp" method="get" onsubmit="show_array(chats)" >
<p>
<textarea id="chatlet" rows="10" cols="30"></textarea>
</p>
<input type="submit" value="Send Chat">
</form>
</body>
</html>
You need to add return keyword with onsubmit like onsubmit="return show_array(chats)" and then return false in the JS function.
Code:
<form action="agenda2.jsp" method="get" onsubmit="return show_array(chats)" >
JS
counter = 0;
var chats = [];
function show_array(array) {
array[counter] = document.getElementById("chatlet").value;
for (x = 0; x < array.length; x++) {
document.write(array[x] + "<br/>");
}
counter++;
return false;
}
DEMO
Using query you could do below
$('form').submit(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: $(this).attr('action'),
data: 'get form data',
success: function (res) {
// handle response here
}
});
});
In the end of your function show_array() you have to add return false; Or in other case you might concider using jQuery and do this:
Give your form a class or id
<form class="myform">
....
</form>
<script>
$("myform").on('submit', function(e) {
e.preventDefault();
});
</script>
Regards!

Add a checkbox for the innerHTML in javascript

I have a page which contains a 10 items(formatted list).Here in this page I need to add check box for each item and add the item as the value to each check box.when the user click on the check box the selected value should be passed to a new page.Can anyone help me how to add a check box for the innerHTML in java script.
Code:
var newsletter=document.getElementById("block-system-main");
var districolumn=getElementsByClassName('view-id-_create_a_news_letter_',newsletter,'div');
if(districolumn!=null)
{
var newsletterall=newsletter.getElementsByTagName('li');
alert(newsletterall[0].innerHTML);
var all=newsletter.innerHTML;
newsletter.innerHTML="<input type='button' onclick='changeText()' value='Change Text'/>";
}
function changeText()
{
alert("dfgsdg");
}
I don't exactly understand what each part of your code is doing, but i'll try and give a general answer:
In your HTML, do something like this:
<form id="myForm" action="nextPage.com">
<div id="Boxes"></div>
</form>
Change the above names to wherever you want your checkboxes to be written.
And your function:
function changeText()
{
for(var i=0 ; i < newsletterall.length ; i++)
{
var inner = document.getElementById("Boxes").innerHTML;
var newBox = ('<input type="checkbox" name="item[]" value="' + newsletter[i] + '>' + newsletterall[i]);
document.getElementById("Boxes").innerHTML = inner + newBox;
}
document.getElementById("myForm").submit();
}
The last line of code submits the checkboxes automatically. If you don't want that, remove that line, and add a submit button to the form myForm.
​
$('ul​​​#list li').each(
function() {
var me = $(this),
val = me.html(),
ckb = $('<input type="checkbox" />');
ckb.click(function() {
var where=val;
window.location.href='http://google.com/?'+where;
});
me.html('');
me.append(ckb).append($('<span>'+val+'</span>'));
}
);​​​​

Categories