trying to add a checkbox dynamically with jquery but nothing apepars - javascript

Just trying to create a very basic to-do app and for whatever reason, my checkboxes are not showing up.
html:
<div class="todo-box">
<input id="first-contact" type="text" placeholder="what do you have to do?"></input>
<button>submit</button>
<div id="list-section">
</div>
</div>
and jquery:
$( document ).ready(function() {
$('button').on('click', function() {
var a = $('#first-contact').val().toLowerCase();
$('<p>').attr('class', 'list-item').append(a).appendTo('#list-section');
$('<input>', {type: "checkbox"}).appendTo('#list-item');
var pAmount = $('#list-section').children().length;
if (pAmount > 6) {
$('#list-section p').last().remove();
}
});
});

You have 2 issues in $('<input>', {type: "checkbox"}).appendTo('#list-item');:
you're using {type: "checkbox"} at the place where jQuery $() expects a domain argument: you must build a complete element in first argument instead
you're appending the element to a list-item id while you created it as a class
This will work:
$( document ).ready(function() {
$('button').on('click', function() {
var a = $('#first-contact').val().toLowerCase();
$('<p>').attr('class', 'list-item').append(a).appendTo('#list-section');
$('<input type="checkbox">').appendTo('.list-item:last');
var pAmount = $('#list-section').children().length;
if (pAmount > 6) {
$('#list-section p').last().remove();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="todo-box">
<input id="first-contact" type="text" placeholder="what do you have to do?"></input>
<button>submit</button>
<div id="list-section">
</div>
</div>
EDIT: modified in response to the OP's comment : added :last modifier to make checkbox added to the just newly created item only.

I think this is what you are going for?
$('button').on('click', function() {
var a = $('#first-contact').val().toLowerCase();
// update here
$('#list-section').append("<p><input type='checkbox' value='"+a+"'></p>");
var pAmount = $('#list-section').children().length;
if (pAmount > 6) {
$('#list-section p').last().remove();
}
});

Related

To do list , I need to add the items to localstorage and get them when the page loads

Anyone help me to add localstorage to this Jquery code : to save the To-Do-List items to the Localstorage
<script type="text/javascript">
$(function() {
$("#add").on("click", function() {
var val = $("input").val();
if(val !== '') {
var elem = $("<li></li>").text(val);
$(elem).append("<button class='rem'>X</button>");
$("#mylist").append(elem);
$("input").val("");
$(".rem").on("click", function() {
$(this).parent().remove();
});
}
});
});
</script>
<h1>My To-Do List</h1>
<input type="text" placeholder="New item" />
<button id="add">Add</button>
<ol id="mylist"></ol>
You can use
window.localStorage.your_data = value
your_data is the name you want to set and value is the value or variable you want to save.

set new element into list with jquery

i try to add a new li element into the list with jquery.
In this example it´s work fine, but when i want to get the value of a input field
with .val() it´s not create a li element.
http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_html_append
my code: http://jsfiddle.net/k1acpxtp/
$(document).ready(function(){
/* Click Event für Button "btn2" */
$('#btn2').click(function(){
/* Fügt ein Elemente in die Liste mit ".append" und
mit ".val()", wird das Value des Input Feldes ausgelesen */
$("ol").append($("#test").val());
});
});
Just change the code to this :
$("ol").append("<li>"+$("#test").val()+"</li>);
You're appending text to an ol element, which is invalid. You need to first create the li, set its text then append that to the ol:
$('#btn2').click(function () {
$('<li />', { text: $('#test').val() }).appendTo('ol');
});
Example fiddle
try with this code( change code where you append value in ol )
$("ol").append("<li>"+$("#test").val()+"</li>);
Use this code instead
$("ol").append("<li>"+$("#test").val()+"</li>);
Try this
$('#btn2').click(function(){
$("ol").append('<li>'+$("#test").val()+'</li>');
});
Working Demo
I'd suggest the following:
$(document).ready(function() {
$('#btn2').click(function(e) {
// preventing the default behaviour of the <button>:
e.preventDefault();
var entered = $('#test').val(),
tag;
// naive check to see if the user entered 'proper' HTML, eg:
// <li>, <li>Some content</li> etc:
if (entered.indexOf('<') === 0 && entered.lastIndexOf('>') === (entered.length - 1)) {
tag = entered;
} else {
// otherwise, if they entered 'li', 'LI' etc, we
// wrap the entered-value with the '<' and '>' to
// form an HTML tag:
tag = '<' + entered + '>';
}
// creating the element, then appending it to
// the <ol>:
$(tag).appendTo('ol');
});
});
$(document).ready(function() {
$('#btn2').click(function(e) {
e.preventDefault();
var entered = $('#test').val(),
tag;
if (entered.indexOf('<') === 0 && entered.lastIndexOf('>') === (entered.length - 1)) {
tag = entered;
} else {
tag = '<' + entered + '>';
}
$(tag).appendTo('ol');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ol></ol>
<form method="post" action="create.html">New Track:
<input type="text" id="test" name="track" placeholder="<tagName>" />
</form>
<button id="btn2">Add Element</button>
Note that I've also added a placeholder attribute to provide guidance for filling in the <input />.
Note that this also does not check validity of the elements you're adding; therefore it will allow you, or your users, to append a <div> to the <ol>, regardless of that action creating invalid HTML.
It may be worth adjusting so that the <li> is created automatically, but the content is supplied by the users:
$(document).ready(function() {
$('#btn2').click(function(e) {
e.preventDefault();
var entered = $('#test').val();
// creating an <li> element:
$('<li>', {
// taking the entered-value to set the element's
// innerHTML:
'html': entered
}).appendTo('ol');
});
});
$(document).ready(function() {
$('#btn2').click(function(e) {
e.preventDefault();
var entered = $('#test').val();
$('<li>', {
'html': entered
}).appendTo('ol');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ol></ol>
<form method="post" action="create.html">New Track:
<input type="text" id="test" name="track" placeholder="new content" />
</form>
<button id="btn2">Add Element</button>
References:
appendTo().
event.preventDefault().

Supply new code to a DIV if content within it is removed

I wonder if it's possible in jQuery/JS:
If “foobar” is removed or gone from the HTML code
<div id="foo">
<div id="line1">...</div>
<div id="line2">foobar</div>
</div>
I'd like to automatically add “new”
<div id="foo">
<div id="line1">...</div>
<div id="line2">new</div>
</div>
I'd like to have "new" displayed when someone deleted "foobar" from #line2. It's for attribution purposes.
If you make the text the value of an input you can bind to it's change event:
<div id="foo">
<div id="line1">...</div>
<div id="line2"><input type="text" value="foobar" /></div>
</div>
$('#line2').children('input').on('change', function () {
var $this = $(this);
if ($this.val() == '') {
$this.val('new');
}
});
Here is a demo: http://jsfiddle.net/u9Twu/
Note that if you want to programatically change the value of the input you have to manually call .trigger('change') on the input after you change it's value for the change event handler to run.
Also note that .on() is new in jQuery 1.7 and in this case is the same as .bind().
UPDATE
var $foo = $('#foo'),
$line2 = $foo.children('#line2');
if ($line2.length == 0) {
//no #line2 element is found
$foo.append('<div id="line2">new</div>');
} else if ($line2.text().length == '') {
//#line2 element is empty
$line2.text('new');
} else if ($line2.text() != 'foobar') {
//#line2 element does not contain only the string: foobar
$line2.text('new');
}
Here is a demo: http://jsfiddle.net/u9Twu/1/
$('#foo').click(function() {
$('#line2').remove();
$(this).append('<div id="line3">new foobar</div>');
})
http://jsfiddle.net/y5FDs/

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]);
}
}

jQuery events not firing

I have been trying to get this to work. Basically I have a search box that has a default string in it (i.e. Search) and it should go away when the user clicks on the input field.
Here is the code:
HTML:
<form method="get" action="index.php" id="search">
<span id="searchLogo"></span>
<input type='text' name='q' id='searchBox' value="Search <?php print $row[0]?> tweets!" autocomplete="off" />
</form>
Javascript/jQuery: (defaultString is a global variable that has the value of the textbox)
function clearDefault() {
var element = $('#searchBox');
if(element.attr('value') == defaultString) {
element.attr('value',"");
}
element.css('color','black');
}
$('#searchBox').focus(function() {
clearDefault();
});
Problem is here:
if(element.attr('value') == defaultString) {
element.attr('value',"");
}
Change it with:
if(element.val() == defaultString) {
element.val('value');
}
Update: Check it here:
http://jsfiddle.net/mr3T3/2/
The problem was that the event binding was not inside the $(document).ready() handler.
Fixed:
function clearDefault() {
var element = $('#searchBox');
if(element.val() == defaultString) {
element.val("");
}
element.css('color','black');
}
$(document).ready(function() {
$('#searchBox').focus(function() {
clearDefault();
});
});
It could be that event in fact is firing and your problem is in
if(element.attr('value') == defaultString) {
element.attr('value',"");
}
is "defaultString" properly defined?
put a simple alert() inside clearDefaults() and see if the event works.
i don't think clearDefault is reusable function, so don't create unnecessary function for small block of code. See the following code sample, i added a small improvement in your functionality.
<form method="get" action="index.php" id="search">
<span id="searchLogo"></span>
<input type='text' name='q' id='searchBox' default="Search tweets!" value="Search tweets!" autocomplete="off" />
</form>
$(document).ready(function() {
$("#searchBox").focus(function(e){
var $this = $(this);
if($this.val() == $this.attr('default')) $this.val('');
else if($this.val().length == 0 ) $this.val($this.attr('default'));
});
$("#searchBox").blur(function(e){
var $this = $(this);
if($this.val().length == 0 ) $this.val($this.attr('default'));
});
});
I added a default attribute to store default value and used it later on blur event.
See the example in jsFiddler

Categories

Resources