I am trying to create a form which will take the user input to create a query for database. I have three buttons: And, Or, Run.
I am creating dynamic elements on click of buttons And and Or.
The div search_list is the container for containing the elements.
I need the form to be submitted on click of Run.
The weird thing is, whenever I click on any button the form gets submitted. How do I stop it ? Please let me know If you need more info.
Thanks
<html>
<head>
<script type="text/javascript">
var count = 0;
function loadfirst(){
count=1;
addFilter('');
}
function addFilter(flag){
var div = document.querySelector("#search_list");
tr = document.createElement("tr");
select = document.createElement("select");
var sear_value = document.createElement("input");
var and_or = document.createTextNode(flag);
tr.id='tr_'+count;
select.id='sl_'+count;
sear_value.id='sear_value_'+count;
select.options.add( new Option("user id","user_id", true,true) );
select.options.add( new Option("First name","first_name"));
select.options.add( new Option("Last name","last_name"));
select.options.add( new Option("Course","course"));
sear_value.type="text";
if(count<=1){
var bt_and= document.createElement("button");
bt_and.id='and';
var bt_label = document.createTextNode("And");
bt_and.appendChild(bt_label);
bt_and.addEventListener('click', function() {
addFilter('and');
return false;
});
var bt_or= document.createElement("button");
bt_or.id='or';
var bt_label = document.createTextNode("Or");
bt_or.appendChild(bt_label);
bt_or.addEventListener('click', function() {
addFilter('or');
return false;
});
}
else{
var bt_rem= document.createElement("button");
bt_rem.id='rem_'+count;
var bt_label1 = document.createTextNode("x");
bt_rem.appendChild(bt_label1);
var tr_id = 'tr_'+count;
bt_rem.addEventListener('click', function() {
var element= document.getElementById(tr_id);
element.parentNode.removeChild(element);
return false;
});
}
tr.appendChild(and_or);
tr.appendChild(select);
tr.appendChild(sear_value);
if(count<=1){
tr.appendChild(bt_and);
tr.appendChild(bt_or);
}
else{
tr.appendChild(bt_rem);
}
div.appendChild(tr);
count++;
}
function getFilter(){
alert();
}
</script>
</head>
<body onload="loadfirst()">
<span id='manage_stud_header' class= 'list_header'>
<label><?php echo $module_name;?></label>
<center>
<form>
<div id='search_list' class='search'></div>
<button id="run_filter" type="submit">Run</button>
</form>
</center>
</span>
</body>
</html>
The default type for buttons is "submit", so you have to explicitly say you want a plain button:
var bt_and= document.createElement("button");
bt_and.type = "button";
This way it won't submit the form when clicked. (unless of course you tell it to :))
you have to change
<button id = "run_filter" type = "submit" > Run </button>
in
<input id = "run_filter" type = "submit" value="Run" />
and then if the behaviour of click on button is forced to reload the page try to change button on other form element or see e.preventdefaulT of jquery
Related
I am very new to javascripts and trying to create a dynamic html form where there are multiple button, and each button click map to a corresponding form input. Here is my code:
<html>
<head>
<title>Create Group</title>
<script src="/js/jquery-3.4.1.min.js"></script>
<script>
$(document).ready(function(){
$("#generate_form").click(function(){
var number = document.getElementById("number_of_groups").value;
var container = document.getElementById("container");
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
var i;
for (i=1;i<=number;i++){
var p = document.createElement("p");
var node = document.createTextNode("group " + i + " :");
p.appendChild(node);
container.appendChild(p);
var input = document.createElement("input");
input.type = "text";
var thisID = 'group_'+i;
input.id = thisID;
input.name=thisID;
container.appendChild(input);
var button = document.createElement("button");
button.id = "button_"+i;
button.type = "button";
container.appendChild(button);
button.onclick = function(){ document.getElementById(thisID).value = "hello world";};
var buttonLabel = document.createTextNode("Generate");
button.appendChild(buttonLabel);
container.appendChild(document.createElement("br"));
}
})
});
</script>
</head>
<body>
<h2>Create some group(s)</h2>
<br>
Create <input type="text" id="number_of_groups" name="number_of_groups" value="1"> group(s).
<button id="generate_form" type="button">GO</button>
<div id="container"/>
</body>
</html>`
So, the user would input number of groups to create and click 'Go' button, then the code should dynamically generate the form with the number the user choose. Each group of the form includes a input textbox and a 'Generate' button. When the button is clicked, the input textbox will show "hello world". However, the "hello world" only show up in the last input textbox no matter which 'Generate' button I click. So I changed the onclick function of the button to:
button.onclick = function(){ alert(thisID);};
Then I found that thisID is always the id of the last input textbox no matter which 'Generate' button I click. I guess that is because the binding of the click event does not happen till the script is done when 'thisID' would always be its latest value.
Would anyone please help me to realize the functionality I want? Thank you very much!
You would need to wrap the code within the for loop in a separate function, passing in the value of i as a parameter. This would create a closure, creating a new execution scope for your code. Otherwise what is happening is that your var is being hoisted, and is not exclusive to each iteration of the for loop, so your DOM is reflecting only the last value it was assigned.
for (i=1;i<=number;i++){
(function (i) {
var p = document.createElement("p");
var node = document.createTextNode("group " + i + " :");
p.appendChild(node);
container.appendChild(p);
var input = document.createElement("input");
input.type = "text";
var thisID = 'group_'+i;
input.id = thisID;
input.name=thisID;
container.appendChild(input);
var button = document.createElement("button");
button.id = "button_"+i;
button.type = "button";
container.appendChild(button);
button.onclick = function(){ document.getElementById(thisID).value = "hello world";};
var buttonLabel = document.createTextNode("Generate");
button.appendChild(buttonLabel);
container.appendChild(document.createElement("br"));
})(i);
}
You can check out an article on closures here:
https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-closure-b2f0d2152b36
EDIT: As one of your commenters mentioned, you can also set your vars to 'let' to achieve a similar effect. This is because let scopes the variable to the current code block, rather than being hoisted to the scope of the function, so each for loop iteration has a private let variable. It is still recommended to get a good understanding of closures and how they work, however.
Since you are already using JQuery, you can reduce some of the logic.
Let me know if this helps-
<html>
<head>
<title>Create Group</title>
</head>
<script src="/js/jquery-3.4.1.min.js"></script>
<script>
$(document).ready(()=>{
var txtGroup='<input type="text" id="txt_group_{0}" value="">';
var btnGroup='<button id="btn_group_{0}" type="button">Click Me</button>';
var container=$('#container');
$('#generate_form').click((e)=>{
var groupCount=parseInt($('#number_of_groups').val());
var idToStart=$('#container').children('div').length+1;
for(let i=idToStart;i< idToStart+groupCount;i++){
var divGroup=`<div id="div_group_${i}">`+
txtGroup.replace('{0}',i)+
btnGroup.replace('{0}',i)+`</div>`;
container.append(divGroup);
$('#btn_group_'+i).on('click',(e)=>{
console.log('#txt_group_'+i);
$('#txt_group_'+i).val('Hello World');
});
}
});
});
</script>
<body>
<h2></h2>
<br>
Create <input type="text" id="number_of_groups" name="number_of_groups" value="1"> group(s).
<button id="generate_form" type="button">GO</button>
<div id="container"></div>
</body>
</html>
html:
<header>
<h1>ENTER A TASK BELOW</h1>
<input type="text" id="task"><img id="add" src="add.png">
</header>
<div id="incomplete-tasks">
<h4>TO-DO LIST</h4>
<ul id="task-to-do">
</ul>
</div>
javascript / jquery:
$(document).ready(function() {
document.getElementById("add").addEventListener("click", function() {
var taskinput = document.getElementById("task").value;
if (taskinput) {
var tasktext = document.createTextNode(taskinput);
var list = document.createElement("li");
list.appendChild(tasktext);
var button = document.createElement("button");
button.setAttribute("class", "completed");
button.innerHTML = "X";
list.appendChild(button);
var toDoList = document.getElementById("task-to-do");
toDoList.insertBefore(list, toDoList.childNodes[0]);
document.getElementById("task").value = " ";
} else {
alert("Please enter a task");
}
});
$(document).on('click', "button.completed", function() {
$(this).closest("li").remove();
});
});
This is a simple to-do list I am working on. One of the things I have put in place is for an alert box to pop up if the user hits the "add" image/button without inputting anything into the field below "Enter a task".
However, something is wrong and it is allowing the user to add empty input values. I can not see what I am doing wrong here. Please can someone assit? Many thanks!
I made a small correction in your javascript/jquery code.In the if condition I added the trim() method to check if there is an empty characters string.
$(document).ready(function() {
document.getElementById("add").addEventListener("click", function() {
var taskinput = document.getElementById("task").value;
if ($.trim(taskinput)!== '') {
var tasktext = document.createTextNode(taskinput);
var list = document.createElement("li");
list.appendChild(tasktext);
var button = document.createElement("button");
button.setAttribute("class", "completed");
button.innerHTML = "X";
list.appendChild(button);
var toDoList = document.getElementById("task-to-do");
toDoList.insertBefore(list, toDoList.childNodes[0]);
document.getElementById("task").value = " ";
} else {
alert("Please enter a task");
}
});
$(document).on('click', "button.completed", function() {
$(this).closest("li").remove();
});
});
I have a 'like' button; and underneath the button, I can display the 'like count'.
However, I want the 'like count' value to be displayed on the actual button itself. For example, I want the button to say: "Like 5"
How can I display both text and a variable value on a button?
Maybe you can improving with this code that i did.
HTML
<form id = "form" method = "POST">
<input type = "submit" value = "Like" />
</form>
<br />
<div id = "clicks">
counter = <label id = "count">0</label> clicks !
</div>
JS
function CountOnFormSubmitEvent(form_id, _callback_)
{
var that = this, count = 0, callback = _callback_;
var form = document.getElementById(form_id);
if(form === null) { return null; }
var reset = function(){
count = 0;
};
form.addEventListener("submit", function(evt){
callback(evt, ++count, reset);
}, false);
}
//Reseting Process You can delete if you dont want it.
var counter = new CountOnFormSubmitEvent("form", function(event, count, reset_callback){
event.preventDefault();
if(count >= 10)
{
alert("Reseting the process");
reset_callback();
}
document.getElementById("count").innerHTML = count;
});
Here is the link Jsfiddle.
DEMO JSFIDDLE
Attempting my first Javascript project, playing around with DOM to make a To-Do List.
After adding an item, how do i get the 'Remove' button to function and remove the item + the remove button.
Furthermore, after a new entry is made, the list item still stays in the input field after being added. How can it be made to be blank after each list item.
And yes i know my code is kinda messy and there is most likely an easier way to create it but I understand it like this for now.
Any help is greatly appreciated. Thanks
JSFiddle Link : http://jsfiddle.net/Renay/g79ssyqv/3/
<p id="addTask"> <b><u> Tasks </u></b> </p>
<input type='text' id='inputTask'/>
<input type='button' onclick='addText()' value='Add To List'/>
function addText(){
var input = document.getElementById('inputTask').value;
var node=document.createElement("p");
var textnode=document.createTextNode(input);
node.appendChild(textnode);
document.getElementById('addTask').appendChild(node);
var removeTask = document.createElement('input');
removeTask.setAttribute('type', 'button');
removeTask.setAttribute("value", "Remove");
removeTask.setAttribute("id", "removeButton");
node.appendChild(removeTask);
}
You can simply assign event:
removeTask.addEventListener('click', function(e) {
node.parentNode.removeChild(node);
});
http://jsfiddle.net/g79ssyqv/6/
Edited the Fiddle... just try this
FiddleLink (Should work now, button and p-tag will be removed)
HTML
<p id="addTask"> <b><u> Tasks </u></b> </p>
<input type='text' id='inputTask'/>
<input type='button' onclick='addText()' value='Add To List'/>
JS
var row = 0;
function addText(){
var input = document.getElementById('inputTask').value;
if(input != "")
{
var node=document.createElement("p");
var textnode=document.createTextNode(input);
node.appendChild(textnode);
node.setAttribute("id","contentP"+row);
document.getElementById('addTask').appendChild(node);
var removeTask = document.createElement('input');
removeTask.setAttribute('type', 'button');
removeTask.setAttribute("value", "Remove");
removeTask.setAttribute("id", "removeButton");
removeTask.setAttribute("onClick", "deleterow("+ row +");");
node.appendChild(removeTask);
row++;
}
else
{
alert("Please insert a value!");
}
}
function deleterow(ID)
{
document.getElementById('contentP'+ID).remove();
}
Greetings from Vienna
Use this
// +your code
.....
node.appendChild(removeTask);
// + modify
removeTask.onclick = function(e){
var dom = this;
var p_dom = this.parentNode;
console.log(p_dom);
var parent_node = p_dom.parentNode;
parent_node.removeChild(p_dom);
}
I'm dynamically adding text inputs to a form. The new input also receives focus. On adding an onblur event however the onblur event seems to be firing as soon as the input is added. To test this I added an alert for the onblur event. The alert appears, and only after clicking OK is the new input created. This happens in IE, Firefox and Opera.
The following is the code I am using. I have removed all other code to for ease of reading.
<head><title>""</title>
<script type="text/javascript">
var count = 1;
function addinput () {
var inpmaster = document.getElementById("inpMaster");
var myinput = document.createElement("input");
myinput.id = "myfield"+count;
myinput.name = "myfield"+count;
myinput.type = "text";
myinput.onblur = alert("woot");
inpmaster.parentNode.insertBefore(myinput,inpmaster);
inpmaster.disabled="disabled";
myinput.focus();
count++;
};
</script>
</head>
<body>
<form action="" method="post" id="admin">
<input id="inpMaster" type="text" name="prodDesccc" onfocus="addinput();" />
</form>
</body>
It is because you are using alert("woot") to assign to onblur event instead of function(){ alert("woot") ;}.
Change your code to:
function addinput () {
var inpmaster = document.getElementById("inpMaster");
var myinput = document.createElement("input");
myinput.id = "myfield"+count;
myinput.name = "myfield"+count;
myinput.type = "text";
myinput.onblur = function(){alert("woot");};
inpmaster.parentNode.insertBefore(myinput,inpmaster);
inpmaster.disabled="disabled";
myinput.focus();
count++;
};