How can I populate an input field with a .val()? - javascript

I'm trying to edit list items that I have and I want to set the text of the parent section to the form field with .val(). I also want to remove it from the local storage as well, problem is I have no idea how to do this and it doesn't seem to be to popular online because I can't find it anywhere.
This is how I'm bringing in the data through the input form:
function addTodo(form) {
var input = $(form).find('input[name="todo"]').first();
if (input) {
var todo = input.val();
if (Modernizr.localstorage) {
var todo_list = {};
if (localStorage.todos) {
todo_list = JSON.parse(localStorage.todos);
}
var id = +new Date;
todo_list[id] = {
name: todo,
completed: false
};
localStorage.todos = JSON.stringify(todo_list);
drawTodos();
}
input.val('');
}
if ( jQuery.fn.validate ) {
$(form).validate().resetForm();
}
}
How would I select a list item that I've added so that it will end up back in the input feild so I can edit it?
<section>
<h1>List</h1>
</section>
<section id="todo_list">
<header>
<form>
<input type="text" name="todo" placeholder="What do you need to do?" />
<input type="submit" name="add_todo" value="Add To List" />
</form>
</header>
</section>
I have some html generating in a loop within the jquery:
<section class="todo_item" id="item' + id + '"><span id="complete" class="colour complete">Complete</span><span id="incomplete" class="colour incomplete">Incomplete</span><span class="content editable" id="done">' + todo.name + '</span><img src="img/delete.png" /></section>

Why don't you attach a handler to the span that has editable class?
Something like this:
$(document).ready(function () {
$(".content.editable").click(function () {
$("input[name='todo']").val($(this).text());
});
});
Please note, IDs must be unique. It is an error to assign the same ids: 'done', 'incomplete', 'complete' to several sections.

Related

How to dynamically add and remove text input fields in Svelte correctly?

I am new to Svelte and web development and I hope you could point me in the right direction.
The current code belongs in a svelte component.
As shown here: https://svelte.dev/repl/f0e5c30117724ec38b7d19781d2c4de6?version=3.48.0
It is supposed to show one text field by default, while allowing for an additional text field to be added and removed on dynamically added buttons.
Currently, this code can dynamically add the text field, however, it cannot dynamically remove the text field on button click.
I believe there might be an error in the GetDynamicElement function. However, I am not sure where exactly. Any suggestions?
p.s. I know there are answers here that are close, but I don't think they are applicable in this situation, especially on Svelte.
<script>
var num_links = 1;
let container;
const GetDynamicElement = (value) => {
return (
'<input name = "DynamicField" type="text" size =111 id =link placeholder="Enter Next link! " value = "' +
value +
'" />' +
'<input type="button" value="Remove" on:click = {RemoveField(this)}>'
// "RemoveSuggestionCart(this)" />'
);
};
const addField = () => {
if (num_links < 2) {
console.log("addField");
const div = document.createElement("DIV");
div.innerHTML = GetDynamicElement("");
container.appendChild(div); // Append timetable space
num_links += 1;
}
};
//Removes the entire division inclusive of it's text field.
const RemoveField = (div) => {
console.log("RemoveField");
div.removeChild(div.parentNode);
num_links -= 1;
};
</script>
<div>
<input
name="DynamicField"
type="text"
size="121"
id="link"
placeholder="Enter First Link!"
/>
<div bind:this={container} />
</div>
<button on:click|preventDefault={addField}>[+ add timetable link]</button>
<style>
</style>
Add/ remove fields and have a button to log or send to endpoint or whatever with "Log" button.
<script>
// to display one empty inputs before clicking add needed
let values=[{
"url": "",
"name": "",
}];
const addField = () => {
values = [...values, {url: '', name: ''}]
};
const removeField = () => {
values = values.slice(0, values.length-1)
};
</script>
{#each values as v, i}
<div>
<input id={i} type="text" bind:value={values[i].url} placeholder="url"/>
<input id={i} type="text" bind:value={values[i].name} placeholder="name"/>
</div>
{/each}
{#if values.length >= 2}
<input type="button" value="Remove" on:click={removeField}>
{/if]
<button on:click|preventDefault={addField}>Add</button>
<button on:click={() => console.log(values)}>Log Me</button>
Try: https://svelte.dev/repl/2441993f8d9946aa894bf07a8a8f9b4f
Edited: thanks #Corrl - edited nicer.
You can use your num_link and svelte's #each to create to inputs using svelte:
{#each Array(num_links) as _, i}
<div>
<input
name="DynamicField"
type="text"
size="121"
id={`link_${i}`}
placeholder="Enter First Link!"
/>
</div>
{/each}
Working example: https://svelte.dev/repl/04169e030b6944258cfd07af15873b48?version=3.48.0

how to get an array post values

In my script, I have input fields which are added dynamically. I have to get all input values using php but the problem in that $_POST['poids'] give me just the first value of input array, so just the first element of the array poids. This is my code:
$(function() {
var max_fields = 10;
var $wrapper = $(".container1");
var add_button = $(".add_form_field");
$(add_button).click(function(e) {
e.preventDefault();
const vals = $("> .item input[name^=poids]", $wrapper).map(function() {
return +this.value
}).get()
const val = vals.length === 0 ? 0 : vals.reduce((a, b) => a + b);
if ($("> .item", $wrapper).length < max_fields && val < 100) {
const $form_colis = $(".item").first().clone();
$form_colis.find("input").val("");
$wrapper.append($form_colis); //add input box
} else {
var err_msg = 'limit riched';
//alert(err_msg);
window.alert(err_msg);
}
});
$wrapper.on("click", ".delete", function(e) {
e.preventDefault();
$(this).parent('div').remove();
})
});
<div class="container1" style="min-height:200px">
<button class="add_form_field">Add New Field ✚</button>
<form method="post" action="postForm.php">
<div class="item">
<input type="text" placeholder="Poids" name="poids[]">
<input type="text" placeholder="Longueur" name="longueurs[]">
<input type="text" placeholder="Largeur" name="largeurs[]">
<input type="text" placeholder="Hauteur" name="hauteurs[]">
Delete
</div>
<button type="submit" name="" class="btn btn-danger btn-responsive "> Send </button></center>
</a>
</form>
</div>
to get post (postForm.php):
$poids = $_POST['poids'];
foreach($poids as $poid) {
echo " -->" .$poid;
}
I hope that you undestand what I mean.
Thank you in advance
The problem is that you're appending the div with the new input fields to $wrapper, but that's outside the form. You need to put it inside the form.
Change
$wrapper.append($form_colis); //add input box
to
$('.item', $wrapper).last().after($form_colis); //add input box
I'm no PHP expert, but by just browsing the code provided, it seems you're just searching for inputs with a name value of poids.
const vals = $("> .item input[name^=poids]",$wrapper).map(function() { return +this.value }).get()
Then when you create a bew input, you do not append poids to the input name.
const $form_colis = $(".item").first().clone();
$form_colis.find("input").val("");
$wrapper.append($form_colis);
Therefore, you will only find one with your method, and that's this one:
<input type="text" placeholder="Poids" name="poids[]">
So to solve this, inside the $form_colis method, add poids to it I do believe.

I am trying to make a checklist where I can click on the button attributed to each "task" and the single line is removed when it is clicked.

Like the question says. I have been able to rid the entire list with a click of a single button (not what I want), I have been able to click a button and rid just the button but not the text - this is what is giving me the biggest issue.
Any help would be greatly greatly appreciated.
//create the initial todocount variable
var toDoCount = 0;
window.onload = function() {
//user clicked on the add button in the to-do field add that text into the to-do text
$('#add-to-do').on('click', function(event) {
event.preventDefault();
//assign variable to the value entered into the textbox
var value = document.getElementById('to-do').value;
//test value
console.log(value);
var todoitem = $("#to-dos");
todoitem.attr("item-");
//prepend values into the html and add checkmark, checkbox, and line break to make list
var linebreak = "<br/>";
var todoclose = $("<button>");
todoclose.attr("data-to-do", toDoCount);
todoclose.addClass("checkbox");
todoclose.text("☑");
//prepend values to html
$("#to-dos").prepend(linebreak);
$("#to-dos").prepend(value);
$("#to-dos").prepend(todoclose);
toDoCount++;
//to remove item from checklist
$(document.body).on("click", ".checkbox", function() {
var toDoNumber = $(this).attr("data-to-do");
$("#to-dos").remove();
});
});
HTML below
<div class ="col-4">
<!-- To Do List -->
<form onsubmit= "return false;">
<span id = "todo-item" type = "text">
<h4>Add your Agenda Here</h4>
<input id ="to-do" type = "text">
<input id ="add-to-do" value = "Add Item" type = "submit">
</span>
</form>
<div id="to-dos"></div>
</div>
This should work.
//create the initial todocount variable
var toDoCount = 0;
$(function() {
//user clicked on the add button in the to-do field add that text into the to-do text
$('#add-to-do').on('click', function(event) {
event.preventDefault();
//assign variable to the value entered into the textbox
var value = document.getElementById('to-do').value;
//test value
console.log(value);
var todoitem = $("#to-dos");
todoitem.attr("item-");
//prepend values into the html and add checkmark, checkbox, and line break to make list
var linebreak = "<br/>";
var todoclose = $("<button>");
todoclose.attr("data-to-do", toDoCount);
todoclose.addClass("checkbox");
todoclose.text("☑");
//prepend values to html
$("<div/>", {
"class": "to-do-item"
})
.append([todoclose, value, linebreak])
.appendTo($("#to-dos"));
toDoCount++;
//to remove item from checklist
$(document.body).on("click", ".to-do-item", function() {
var toDoNumber = $('.checkbox', this).attr("data-to-do");
$(this).remove();
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-4">
<!-- To Do List -->
<form onsubmit="return false;">
<span id="todo-item" type="text">
<h4>Add your Agenda Here</h4>
<input id ="to-do" type = "text">
<input id ="add-to-do" value = "Add Item" type = "submit">
</span>
</form>
<div id="to-dos"></div>
</div>
I found the root issue to be related to how you remove the item. If it is based on the button click, then $(this).remove() simply removes the button.
Consider the following code.
$(function() {
function makeTask(todo) {
var c = $("#to-dos .todo-item").length + 1;
console.log(c, todo);
var item = $("<div>", {
class: "todo-item",
id: "todo-item-" + c
});
$("<button>", {
class: "checkbox todo-item-close",
id: "todo-item-close-" + c
}).html("☑").click(function(e) {
console.log("Remove", $(this).parent().attr("id"));
$(this).parent().remove();
}).appendTo(item);
item.append(todo);
return item;
}
$('form').submit(function(e) {
e.preventDefault();
var task = makeTask($("#to-do").val());
task.appendTo("#to-dos");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-4">
<!-- To Do List -->
<form>
<h4>Add your Agenda Here</h4>
<input id="to-do" type="text" />
<input id="add-to-do" value="Add Item" type="submit" />
</form>
<div id="to-dos"></div>
</div>
Here we add the button and assign a click event to that button. Since the button is inside the <div> we need to traverse to the parent element and then remove the entire element.
Since it is in a form, and many users may try to submit the data with Enter, I prefer to use .submit() callback.
Hope that helps.

get multiple values from an input tag with js

im trying to write a code that will generate me several "input" tags to a html
page.
i want to make something like this:
<div id="here">
<input type='text' placeholder='book'>
<input type='text' placeholder='author'>
</div>
<button id="another-book">+</button>
each time that the button is clicked i want to add another input to the page
right after the previous input.
i do it in a js file with the code:
$('#another-book').click(function (e) {
$('#here').append($("<input type='text' placeholder='book'>");
$('#here').append($("<input type='text' placeholder='author'>");
});
my problem is that after the user created his inputs and filled them,
i want to get the values of them - for each pair of book and author,
i.e. i want to get in the end a list of pairs (book, author)
how can i do that?
Try something like this
$('#another-book').click(function(e) {
console.log($('#here').find('input').map(function() {
return this.value
}).get());
$('#here').append($("<input type='text' placeholder='book'>"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="here">
<input type='text' placeholder='book'>
</div>
<button id="another-book">+</button>
There is extra $( without closing bracket.
this works for me
$('#another-book').click(function (e){
$('#here').append($("<input type='text' placeholder='book'>"));
});
EDIT:
to get book and author pair use this code from jsfiddle
To get first pair take first element from authors array and first from books.
Hope it helped
$('#another-book').click(function (e) {
var a = $('<input>', { text:"", type:"text", placeholder:"book" });
var b = $('<input>', { text:"", type:"text", placeholder:"author" });
var c = $('<span>',{}).append(a).append(b);
$('#here').append(c);
});
$('#g-val').click(function(){
var all = [];
$('#here > span').each(function(){
var $book = [
$(this).find('input[placeholder=book]').val() ,
$(this).find('input[placeholder=author]').val()
]
all.push($book);
});
console.log(all)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="here">
<span>
<input type='text' placeholder='book'>
<input type='text' placeholder='author'>
</span>
</div>
<button id="another-book">+</button>
<h4 id="s-value"></h4>
<button id="g-val">get all input[type=text] ...</button>
For values of all inputs in an array
$.map($("#here").find("input"),function(o,i){return $(o).val();});
EDIT
For list of pairs
$.map( $("#here").find("input[placeholder='book']"),
function(o,i){
var book = $(o).val();
var author = $(o).next("input[placeholder='author']").val();
if (book == "" || author == "")
{
$(o).remove();
$(o).next("input[placeholder='author']").remove();
}
else
{
return { "book": book,
"author": author };
}
}
);

adjusting default value script to work with multiple rows

I am using a default value script (jquery.defaultvalue.js) to add default text to various input fields on a form:
<script type='text/javascript'>
jQuery(function($) {
$("#name, #email, #organisation, #position").defaultvalue("Name", "Email", "Organisation", "Position");
});
</script>
The form looks like this:
<form method="post" name="booking" action="bookingengine.php">
<p><input type="text" name="name[]" id="name">
<input type="text" name="email[]" id="email">
<input type="text" name="organisation[]" id="organisation">
<input type="text" name="position[]" id="position">
<span class="remove">Remove</span></p>
<p><span class="add">Add person</span><br /><br /><input type="submit" name="submit" id="submit" value="Submit" class="submit-button" /></p>
</form>
I am also using a script so that users can dynamically add (clone) rows to the form:
<script>
$(document).ready(function() {
$(".add").click(function() {
var x = $("form > p:first-child").clone(true).insertBefore("form > p:last-child");
x.find('input').each(function() { this.value = ''; });
return false;
});
$(".remove").click(function() {
$(this).parent().remove();
});
});
</script>
So, when the page loads there is one row with the default values. The user would then start adding information to the inputs. I am wondering if there is a way of having the default values show up in subsequent rows that are added as well.
You can see the form in action here.
Thanks,
Nick
Just call .defaultValue this once the new row is created. The below assumes the format of the columns is precticable/remains the same.
$(".add").click(function() {
var x = $("form > p:first-child");
x.clone(true).insertBefore("form > p:last-child");
x.find('input:not(:submit)').defaultvalue("Name", "Email", "Organisation", "Position");
return false;
});
You should remove ids from the input fields because once these are cloned, the ids, classes, everything about the elements are cloned. So you'll basically end up with multiple elements in the DOM with the same id -- not good.
A better "set defaults"
Personally I would remove the "set defaults plugin" if it's used purely on the site for this purpose. It can easily be re-created with the below and this is more efficient because it doesn't care about ordering of input elements.
var defaults = {
'name[]': 'Name',
'email[]': 'Email',
'organisation[]': 'Organisation',
'position[]': 'Position'
};
var setDefaults = function(inputElements)
{
$(inputElements).each(function() {
var d = defaults[this.name];
if (d && d.length)
{
this.value = d;
$(this).data('isDefault', true);
}
});
};
Then you can simply do (once page is loaded):
setDefaults(jQuery('form[name=booking] input'));
And once a row is added:
$(".add").click(function() {
var x = $("form > p:first-child");
x.clone(true).insertBefore("form > p:last-child");
setDefaults(x.find('input')); // <-- let the magic begin
return false;
});
For the toggling of default values you can simply delegate events and with the help of setDefault
// Toggles
$('form[name=booking]').delegate('input', {
'focus': function() {
if ($(this).data('isDefault'))
$(this).val('').removeData('isDefault');
},
'blur': function() {
if (!this.value.length) setDefaults(this);
}
});
Fiddle: http://jsfiddle.net/garreh/zEmhS/3/ (shows correct toggling of default values)
Okey, first of all; ids must be unique so change your ids to classes if you intend to have more then one of them.
and then in your add function before your "return false":
var
inputs = x.getElementsByTagName('input'),
defaults = ["Name", "Email", "Organisation", "Position"];
for(var i in inputs){
if(typeof inputs[i] == 'object'){
$(inputs[i]).defaultvalue(defaults[i]);
}
}

Categories

Resources