I have a form, and I would like to clear the input field every time I enter the submit (plus) button.
I have tried using this, it does not work. I may be implementing it in the wrong spot.
document.getElementById('add-item').value='';
My Javascript code is below.
window.addEventListener('load', function(){
// Add event listeners
document.getElementById('add-item').addEventListener('click', addItem, false);
document.querySelector('.todo-list').addEventListener('click', toggleCompleted, false);
document.querySelector('.todo-list').addEventListener('click', removeItem, false);
function toggleCompleted(event) {
console.log('=' + event.target.className);
if(event.target.className.indexOf('todo-item') < 0) {
return;
}
console.log(event.target.className.indexOf('completed'));
if(event.target.className.indexOf('completed') > -1) {
console.log(' ' + event.target.className);
event.target.className = event.target.className.replace(' completed', '');
document.getElementById('add-item').value='';
} else {
console.log('-' + event.target.className);
event.target.className += ' completed';
}
}
function addItem() {
var list = document.querySelector('ul.todo-list');
var newItem = document.getElementById('new-item-text').value;
var newListItem = document.createElement('li');
newListItem.className = 'todo-item';
newListItem.innerHTML = newItem + '<span class="remove"></span>';
list.insertBefore(newListItem, document.querySelector('.todo-new'));
}
function removeItem(event) {
if(event.target.className.indexOf('remove') < 0) {
return;
}
var el = event.target.parentNode;
el.parentNode.removeChild(el);
}
});
This is what you need:
document.getElementById('new-item-text').value = "";
regarding your need, you will need to put it at the end of your addItem()
you can refer this simple code:
<html>
<body>
<input type="text" id="test">
<button onclick="func()">remove</button>
<br/>
Value = <span id="val"></span>
<script>
function func(){
alert("clicked");
document.getElementById('val').innerHTML = document.getElementById('test').value;
document.getElementById('test').value = '';
}
</script>
</body>
</html>
Use form reset method to clear inputs in one go.
document.getElementById("myForm").reset();
You can set your textbox value = '' in submit button.
and you can create a ClearFunction and then you can call it everytime you need it.
function cleartextbox() {
$('#name').val("").focus();
$('#selectgender').val("");
$('#telephone').val("");
}
Related
I'm trying to write a CRUD app. I'm having trouble figuring out how to edit and delete individual items. For each item created, I'm making two <a> tags inside of a <span> tag. One for edit and one for delete. But I can't seem to figure out how to make them do what they need to do. At this point they don't do anything because I can't figure out how to access the values correctly.
Note - I'm just beginning to learn jQuery so, any pro tips on that are appreciated.
Here's the html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<form class='form'>
<input id="input" type="text" placeholder="Type here..">
</form>
<h3>Notes</h3>
<ul></ul>
<button id='clear'>Clear All</button>
</div>
<script src="app.js"></script>
</body>
</html>
And the javascript:
const app = {};
app.counter = (function(){
var i = -1;
return function(){
i += 1;
return i;
}
})()
app.create = function(element){
return document.createElement(element);
}
app.select = function(element){
return document.querySelector(element);
}
app.makeList = function(text) {
var i = app.counter();
var li = app.create('li');
var div = app.create('span');
var edit = app.create('a');
var del = app.create('a');
li.textContent = text;
edit.textContent = ' Edit';
edit.href = '#'
del.textContent = ' Delete';
del.href = '#'
div.appendChild(edit);
div.appendChild(del);
li.appendChild(div);
ul.insertBefore(li, ul.childNodes[0])
li.id = 'item' + i;
del.id = 'delete' + i;
edit.id = 'edit' + i;
}
// constants & variables
const ul = app.select('ul')
const input = app.select('input')
var notes;
$(document).ready(function(){
if (localStorage.getItem('notes')) {
notes = JSON.parse(localStorage.getItem('notes'));
} else {
notes = [];
}
localStorage.setItem('notes', JSON.stringify(notes));
// build list items and display them on the page
JSON.parse(localStorage.getItem('notes')).forEach(function(item){
app.makeList(item);
});
// when form is submitted
$('.form').submit(function(e){
e.preventDefault();
if (input.value.length > 0){
notes.push(input.value);
localStorage.setItem('notes', JSON.stringify(notes));
app.makeList(input.value);
input.value = "";
}
})
// clear items on page and from local storage
$('#clear').click(function(){
if (window.confirm('This will clear all items.\nAre you sure you want to do this?')){
localStorage.clear();
while (ul.firstChild) {
ul.removeChild(ul.firstChild)
}
}
});
$('ul').on('click', 'li', function(){
console.log(this.textContent) // logs whatever is typed + Edit Delete
})
});
Do something like this.
$("ul").on("click", "li", function(e) {
console.log(this.textContent); // logs whatever is typed + Edit Delete
if(e.target.id === "edit") {
//edit
}
if(e.target.id==="delete") {
//delete
}
});
You are trying to access elements before they are ready that is why you are not able to see anything.
Declare them on global level but assign them value after the document is ready.
var ul;
var input;
var notes;
$(document).ready(function () {
ul = app.select('ul')
input = app.select('input')
...Rest of your code
});
For the Edit and Delete Functionality
As you are appedning IDs in edit and delete button you need to parse that as well
$('ul').on('click', 'li', function (e) {
if (e.target.id.includes('edit')) {
console.log(` item ${e.target.id.split('edit')[1]} needs to be edited.`)
}
if (e.target.id.includes('delete')) {
//delete
}
})
I created a form dynamically with javascript. Now I have to add validations on the form (only mandatory validations) on click of the button which is also dynamically created. Now the issue I am facing is that whenever I try to add addEventListener on the button exactly after creating it, it is giving me error.
(
function init() {
console.log("div created");
// create a new div element
var newDiv = document.createElement("div");
newDiv.id = "registration_form";
var createForm = document.createElement("form");
newDiv.appendChild(createForm);
var heading = document.createElement("h2");
heading.innerHTML = "Registration Form";
createForm.appendChild(heading);
var linebreak = document.createElement('br');
createForm.appendChild(linebreak);
createElement(createForm, 'label','','','Name: ');
createElement(createForm, 'text', 'dname', '','');
createSpanTag(createForm,'nameError');
breakTag(createForm);breakTag(createForm);
createElement(createForm, 'label','','','Email: ');
createElement(createForm, 'email', 'email', '','');
createSpanTag(createForm,'emailError');
createElement(createForm, 'button','Validate','Validate','');
document.getElementsByTagName('button')[0].addEventListener('click',validate());
document.getElementsByTagName('body')[0].appendChild(newDiv);
}
)();
function createElement(formElement,type,name,value, placeholder) {
if(type=='label'){
var element=document.createElement(type);
if(name!='' && value!=''){
element.setAttribute('name',name);
element.setAttribute('value',value);
}
element.innerHTML=placeholder;
formElement.appendChild(element);
} else {
var element=document.createElement('input');
if(type!=''){
element.setAttribute('type',type);
}
if(name!=''){
element.setAttribute('name',name);
}
if(value!=''){
element.setAttribute('value',value);
}
if(placeholder!=''){
element.setAttribute('placeholder',placeholder);
}
formElement.appendChild(element);
}
}
function breakTag(createForm){
createForm.appendChild(document.createElement('br'));
}
function validate(){
}
function createSpanTag(createForm, id){
var element=document.createElement('span');
element.setAttribute('id',id);
createForm.appendChild(element);
}
The second argument of addEventListener needs to be a function.
Change ...
document.getElementsByTagName('button')[0].addEventListener('click',validate())
to ...
document.getElementsByTagName('button')[0].addEventListener('click',validate);
Since your tag name is input, not button. So use input in parameter of the function getElementsByTagName() and then loop through all nodes and find node with type = button.
Try change this line:
document.getElementsByTagName('button')[0].addEventListener('click',validate());
to:
var nodeList = document.getElementsByTagName("input");
for (var i = 0; i < nodeList.length; i++)
{
if (nodeList[i].getAttribute("type") == "button") {
{
nodeList[i].addEventListener('click',validate);
}
}
I'm trying to use jQuery to duplicate my file input groups, so that when the user selects a file to upload, it automatially creates another file upload field and description field.
This works fine, except for when I change the file of a file I've already selected an input for. When I do that, it duplicates ALL the file input groups.
Any insight into why this is going on?
JSFiddle: http://jsfiddle.net/czLmbjd6/4/
HTML:
<div id = "add-photos">
<input type="file"></input>
<label>Description:</label>
<input type = "text"></input>
</div>
<div id = "additional-photos">
</div>
JS:
$(document).ready(function(){
bindFileInputs();
});
function bindFileInputs(){
$("input:file").change(function (){
addPhotoField();
});
}
function addPhotoField() {
var id = 1; //standin for now, will dynamically update this number later
createPhotoField(id);
}
function createPhotoField(id){
var p = $("#add-photos");
p.clone().appendTo("#additional-photos").removeAttr("id").children().find('input,select').each(function(){
$(this).val('');
if ($(this).attr('type') == 'file'){
console.log("type is file");
$(this).attr('name', 'data[Image][' + id + '][image]');
}
if ($(this).attr('type') == 'text'){
console.log("type is text");
$(this).attr('name', 'data[Image][' + id + '][description]');
}
});
bindFileInputs();
}
Try
$(document).ready(function() {
bindFileInputs($('#add-photos input[type="file"]'));
});
function bindFileInputs(input) {
//use one() to register a handler which will be fired only once
input.one('change', function() {
addPhotoField();
});
}
function addPhotoField() {
var id = 1; //standin for now, will dynamically update this number later
createPhotoField(id);
}
function createPhotoField(id) {
var p = $("#add-photos");
var $clone = p.clone().appendTo("#additional-photos").removeAttr("id");
$clone.find('input,select').val('');
$clone.find('input:text').attr('name', 'data[Image][' + id + '][description]');
var $file = $clone.find('input:file').attr('name', 'data[Image][' + id + '][image]');
bindFileInputs($file)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Select a file with the file upload control. It should create a new file input group.
<div id="add-photos">
<input type="file" />
<label>Description:</label>
<input type="text" />
</div>
<div id="additional-photos"></div>
Try this Js:
$(document).ready(function(){
bindFileInputs();
});
function bindFileInputs(){
$("input:file").change(function (){
if($('.newF').length ==0 ){
createPhotoField(Number($(this).attr('id'))+1);
}
if($(this).hasClass('newF')){
createPhotoField(Number($(this).attr('id'))+1);
}
});
}
function createPhotoField(id){
$('.newF').removeClass('newF')
id+=1;
var p = $("<div/>");
p.appendTo("#additional-photos");
p.html('<input class="newF" id= "'+id+'" type="file"></input><label>Description:</label><input type = "text"></input>')
p.children().find('input,select').each(function(){
$(this).val('');
if ($(this).attr('type') == 'file'){
console.log("type is file");
$(this).attr('name', 'data[Image][' + id + '][image]');
}
if ($(this).attr('type') == 'text'){
console.log("type is text");
$(this).attr('name', 'data[Image][' + id + '][description]');
}
})
bindFileInputs();
}
UPDATED FIDDLE:
http://jsfiddle.net/czLmbjd6/12/
See your call of bindFileInputs(); in createPhotoField. You are adding another handler to change event of all $("input:file") elements in your page. If you change the file in any of these elements (except the last one), addPhotoField will fire two or more times.
Do:
var newItem = p.clone();
newItem.appendTo("#additional-photos").removeAttr("id").children().find('input,select').each(function(){
...
});
// instead of bindFileInputs();
newItem.find("input:file").change(function (){
addPhotoField();
});
Well try this
<div id = "add-photos">
<input type="file" inuse="false"></input>
<label>Description:</label>
<input type = "text"></input>
</div>
<div id = "additional-photos">
</div>
$(document).ready(function(){
bindFileInputs();
});
function bindFileInputs(){
$("input:file").change(function (){
if($(this).attr('inuse') == "false"){
addPhotoField();
}
$(this).attr('inuse', 'true');
});
}
var id = 0;
function addPhotoField() {
id += 1; //standin for now, will dynamically update this number later
createPhotoField(id);
}
function createPhotoField(id){
$("#add-photos").find('input:file').attr('inuse', 'false');
var p = $("#add-photos");
p.clone().appendTo("#additional-photos").removeAttr("id").children().find('input,select').each(function(){
$(this).val('');
if ($(this).attr('type') == 'file'){
console.log("type is file");
$(this).attr('name', 'data[Image][' + id + '][image]');
$(this).attr('inuse', 'false');
}
if ($(this).attr('type') == 'text'){
console.log("type is text");
$(this).attr('name', 'data[Image][' + id + '][description]');
}
});
$("#add-photos").find('input:file').attr('inuse', 'true');
bindFileInputs();
}
I am trying this HTML code:
<button name="darkBlue" onclick="setThemeColor(this.name)">Blue</button>
<button name="black" onclick="setThemeColor(this.name)">Black</button>
and script:
function setThemeColor(buttonName) {
localStorage.themeColor = buttonName;
document.getElementsByTagName('html')[0].className = buttonName
var themeButtons = document.querySelectorAll(".theme");
for (var button in themeButtons) {
themeButtons[button].disabled = false;
}
// this.disabled = false;
// element.setAttribute("disabled", "disabled");
}
I am having a problem here setting the disabled state of the button that called the function. Can someone tell me how i can do this. I have tried two things but neither seem to work.
Pass in a reference to your button instead of just the name:
HTML
<button name="darkBlue" onclick="setThemeColor(this)">Blue</button>
<button name="black" onclick="setThemeColor(this)">Black</button>
JS
function setThemeColor(button) {
localStorage.themeColor = button.name;
document.getElementsByTagName('html')[0].className = button.name;
var themeButtons = document.querySelectorAll(".theme");
for (var button in themeButtons) {
themeButtons[button].setAttribute("disabled", "disabled");
}
button.setAttribute("disabled", "disabled");
}
document.getElementById("buttonid1").disabled=false;
I've just created an dynamic HTML form and two of its fields are of type date. Those two fields are posting their data into two arrays. I have 2 issues:
a) The array data are not printed when I press the button.
b) Since I created the arrays to store the data, my dynamic form doesn't seem to be fully functional. It only produces new fields when I press the first "Save entry" button on the form. It also doesn't delete any fields.
My code is:
$(document).ready(function () {
$('#btnAdd').click(function () {
var $address = $('#address');
var num = $('.clonedAddress').length;
var newNum = new Number(num + 1);
var newElem = $address.clone().attr('id', 'address' + newNum).addClass('clonedAddress');
newElem.children('div').each(function (i) {
this.id = 'input' + (newNum * 10 + i);
});
newElem.find('input').each(function () {
this.id = this.id + newNum;
this.name = this.name + newNum;
});
if (num > 0) {
$('.clonedAddress:last').after(newElem);
} else {
$address.after(newElem);
}
$('#btnDel').removeAttr('disabled');
});
$('#btnDel').click(function () {
$('.clonedAddress:last').remove();
$('#btnAdd').removeAttr('disabled');
if ($('.clonedAddress').length == 0) {
$('#btnDel').attr('disabled', 'disabled');
}
});
$('#btnDel').attr('disabled', 'disabled');
});
$(function () {
$("#datepicker1").datepicker({
dateFormat: "yy-mm-dd"
}).datepicker("setDate", "0");
});
var startDateArray = new Array();
var endDateArray = new Array();
function intertDates() {
var inputs = document.getElementsById('datepicker1').value;
var inputsend = document.getElementsById('datepicker2').value;
startDateArray[startDateArray.length] = inputs;
endDateArray[endDateArray.length] = inputsend;
window.alert("Entries added!");
}
function show() {
var content = "<b>Elements of the arrays:</b><br>";
for (var i = 0; i < startDateArray.length; i++) {
content += startDateArray[i] + "<br>";
}
for (var i = 0; i < endDateArray.length; i++) {
content += endDateArray[i] + "<br>";
}
}
JSFIDDLE
Any ideas? Thanks.
On your button you are using element ID's several times, this is so wrong, IDs must be unique for each element, for example:
<button id="btnAdd" onclick="insertDates()">Save entry</button>
</div>
</div>
<button id="btnAdd">Add Address</button>
<button id="btnDel">Delete Address</button>
jQuery will attach the $('#btnAdd') event only on the first #btnAdd it finds.
You need to use classes to attach similar events to multiple elements, and in addition to that simply change all the .click handlers to .on('click', because the on() directive appends the function to present and future elements where as .click() only does on the existing elements when the page is loaded.
For example:
<button id="btnDel">Delete Address</button>
$('#btnDel').click(function () {
[...]
});
Becomes:
<button class="btnDel">Delete Address</button>
$('.btnDel').on('click', function () {
[...]
});
Try this : I know its not answer but it's wrong to get element value using id
Replace
var inputs = document.getElementsById('datepicker1').value;
var inputsend = document.getElementsById('datepicker2').value;
With
var inputs = document.getElementById('datepicker1').value;
var inputsend = document.getElementById('datepicker2').value;
You are using jQuery so i will strongly recommend you to stick with the jQuery selector,
var inputs = $('#datepicker1').val();
var inputsend = $('#datepicker2').val();
where # is used for ID selector.