I want to get an Object in javascript with values from my dynamically generated array in correct order so then later on I will be able to jsonencode that object and save it into my Database. (Maybe there is a different easier way of doing it)
Here is the form
<form name="second_form" id="second_form" action="#" method="POST">
Add Champion
<div id="ChampionInput">
</div>
<input type="submit" name="submit">
</form>
Here are functions that I use to create this array:
$('a#AddChampion').on('click',function(){
$('div#ChampionInput').append(
'<div class="Champion">\
<input type="text" class="ChampionInput">\
Add General Change\
<div class="GeneralChanges">\
</div>\
<div>');
});
$('div#ChampionInput').on('click','a.AddGeneralChange', function(){
$(this).siblings('.GeneralChanges').append(
'<div class="GeneralChange">\
<textarea type="text" size="20" rows="3" cols="50" class="GeneralChangeDescription"></textarea>\
</div>');
});
And below is what I've tried with no result. I was trying to loop through values of my array and then put it into an object I get the whole div instead of the actual value.
$( "#second_form" ).submit( function(event) {
$( "#ChampionInput.ChampionInput :input" ).each( function( index, value ) {
var _value = value;
var _index = index;
alert(value);
$(this).children( ".GeneralChangeDescription").each( function( index, value ) {
});
});
});
Here is a picture of how it could look like after adding some fields http://imgur.com/QXhWSHA
And here is working jSfiddle: http://jsfiddle.net/ss84agxv/
Try this code, I hope that I understood your question correctly.
$("#second_form").submit(function(event) {
//don't do the default action on submit
event.preventDefault();
//Your object as array for the champions
var object = [];
//Loop through each .Champion-div
$('.Champion').each(function() {
//Create a new object for this champion with the value from the input field and an array for the descriptions
var champion = {
'name': $(this).find(".ChampionInput").val(),
'description': []
};
//Loop through each description textfields of this champion
$(this).find('.GeneralChangeDescription').each(function() {
//add the description to the description array of the champion
champion.description.push($(this).val());
});
//finally put the champion in your champion array
object.push(champion);
});
//Thats just for you, an alert of the json-object
alert(JSON.stringify(object));
});
Related
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.
I have an js object that is stored to variable
var data = {
"France":[
{
'population': "8M",
}
],
"Spain":[
{
'population': "18M",
}
]
}
and I have an input field that have some value (choosed from dropdown).
<input type="text" id="country1" onkeyup="myFunction()" placeholder="Select indicator" value="France">
I am trying to compare that value of the input with key of the object, and then if that value is equal to the key, to display population number.
So far I tried to do like this
$( ".compare button" ).click(function() {
var c1 = $( ".first-country input" ).val(); //take value from input
var zemlja = Object.keys(data); //take all keys from object
var n = zemlja.includes(c1); //check if value is included in object
if (n) {
$(".country1-result h1").html(data.c1[0].population); //if value is included, add population number to result
}
});
And I got undefined. I figure it out that I can not take value if I put variable c1 instead of name of the key. If I put name of the key France, everything works fine, but if I put c1 variable that is equal to France, then it is not working.
Any hint/help how to manage this to work.
Thanks.
Since c1 is a variable, use bracket notation which will allow you to use property name as variable:
Change
$(".country1-result h1").html(data.c1[0].population);
To
$(".country1-result h1").html(data[c1][0].population);
var data = { "France": [{ 'population': "8M", }], "Spain": [{ 'population': "18M", }] }
function myFunction(){}
$(".compare").click(function() {
var c1 = $(".first-country").val(); //take value from input
var zemlja = Object.keys(data); //take all keys from object
var n = zemlja.includes(c1); //check if value is included in object
if (n) {
$(".country1-result h1").html(data[c1][0].population); //if value is included, add population number to result
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="country1" onkeyup="myFunction()" placeholder="Select indicator" value="France" class="first-country">
<input type="button" class="compare" value="Click" />
<div class="country1-result">
<h1></h1>
</div>
$( ".compare button" ).click(function() {
var c1 = $( ".first-country input" ).val(); //take value from input
var result = data[c1] ? data[c1][0].population : '';
$(".country1-result h1").html(result);
});
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 };
}
}
);
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.
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]);
}
}