Run jquery plugin with javascript onclick method - javascript

I am using a Jquery plugin for my checkboxes the page of the plugin is this: http://fronteed.com/iCheck/#skin-line
The thing is I used a Javascript function for adding new checkboxes:
function add(){
var userInput = document.getElementById('reg').value;
document.getElementById('checklist').innerHTML = document.getElementById('checklist').innerHTML +
"<li> <input type='checkbox'> <label>"+ userInput + "</label> </li>";
}
$(document).ready(function(){
$(' input').iCheck({
checkboxClass: 'icheckbox_polaris',
radioClass: 'iradio_polaris',
increaseArea: '-10%' // optional
});
});
my HTML where I'm executing the function looks like this:
<p><input type="button" onclick="add()" class="bttns" value="Add"/></p>
</div>
<h3>Added:</h3>
</div>
<div class="scrollpersonalizado">
<ul class="listacheck-radio" id="checklist">
</ul>
</div>
the problem is if I have checkboxes within the:
<ul class="listacheck-radio" id="checklist">
</ul>
when the page loads, they have the style of the plugin, but whenever I click the button and add a new checkbox, this one doesn't get the style of the plugin, and the ones that were there before stop working.
Can anybody please help?
Thanks in advance!

You will need to do two things:
Stop resetting the entire .innerHTML because that wipes out all objects in that sub-hierarchy and creates all new ones (losing all event handlers and styling).
Dynamically create your new elements and use on of the .append() methods and then call .iCheck() on them after creating in order to inherit the new functionality.
Code to do both of those using jQuery:
function add() {
var userInput = $("#reg").val();
$("<li> <input type='checkbox'> <label>"+ userInput + "</label> </li>")
.appendTo("#checklist")
.find("input")
.iCheck({
checkboxClass: 'icheckbox_polaris',
radioClass: 'iradio_polaris',
increaseArea: '-10%' // optional
});
}
Conceptually, this is what this code does:
Get the reg value.
Create a new HTML fragment using the reg value
Append that to the end of the existing checklist
Find the new input tag in that new HTML fragment
Call .iCheck() on it to bless it with the desired behaviors/styles like the other ones.

try this:
$(document).ready(function(){
$('.scrollpersonalizado').on('click', 'input', function(){
var userInput = document.getElementById('reg').value;
$('#checklist').append("<li> <input type='checkbox'> <label>"+ userInput + "</label> </li>");
}).iCheck({
checkboxClass: 'icheckbox_polaris',
radioClass: 'iradio_polaris',
increaseArea: '-10%' // optional
});
});
remove the inline onclick handler from the button try unobtrusive this way with event delegation as you have created your inputs dynamically.

Related

Set jquery mask on a dynamically inserted input?

Set jquery mask on a dynamically inserted input?
I'm trying to do it in the down format, but I'm not succeeding.
The new input loses the mask.
Can someone help me with this please.?
<div class="control">
<input type="text" name="item_valor" placeholder="Valor" class="input valor" maxlength="255" id="id_item_valor">
</div>
.
$(document).ready(function(){
$('.valor').mask("#.##0,00", {reverse: true});
});
.
$(document).on('click', '#addItem', function () {
var newElement = $('.control:last').clone(true);
$('.control:last').after(newElement);
})
set the mask on focus of the input like this
$(document).on("focus", ".valor", function() {
$(this).mask("#.##0,00", {reverse: true});
});
you can probably remove it from document.ready function and also instead of cloning and appending in 2 lines you can shorten it to 1 line with this
$('.control:last').after($('.control:last').clone());
here is a working fiddle https://jsfiddle.net/tv7w3Lku/3/
Side note: cloning an element with ID will create multiple elements with same ID which is probably not the best way, you should just stick with class in this case
Just recall your mask function after each input is added to the DOM.
$(document).on('click', '#addItem', function () {
var newElement = $('.control:last').clone(true);
$('.control:last').after(newElement);
$('.valor').mask("#.##0,00", {reverse: true});
})
I was having this same problem, and discovered the .masked() function will apply the mask to a dynamic value. Hope this helps:
HTML:
<input name="phone" type="text">
<button>insert dynamic value</button>
JS:
$(function(){
$("input[name='phone']").mask("(000) 000-0000");
});
$("button").click(function(){
newPhoneNumber = "1231231234";
maskedValue = $("input[name='phone']").masked(newPhoneNumber));
$("input[name='phone']").val(maskedValue);
});
fiddle: https://jsfiddle.net/qcsf3z0j/4/
and docs: https://igorescobar.github.io/jQuery-Mask-Plugin/docs.html#getting-a-masked-value-programmatically

Create a button to control the JavaScript create some elements. Then if any of these element changes, do something

I'd like to create a button using HTML. If user click the button, then use javascript to create some elements (like checkboxes). After these, if any of the elements changes, do something, like printing out some text.
Following is my code.
HTML:
<button id="try" type="button">TRY</button>
<div id="boxes"></div>
<p id="demo"></p>
Javascript:
doit = function(){
var checkboxes = "";
for(var i = 0;i<5;i++){
checkboxes += "<input type='checkbox' name='a'/>Option" + i+"<br>";
}
$("#boxes").html(checkboxes);
}
$('#try').click(function(){
doit();
})
$("input[name='a']").on("change",function(){
$("#demo").text("success!")
})
I really can't figure out where I am wrong. Demo:https://jsfiddle.net/slfan/cu7tn64o/12/.
Since you are dynamically adding new elements, you need to use a delegate event handler:
$(document).on("change", "input[name='a']", function() {
$("#demo").text("success!")
})
Updated JSFiddle: https://jsfiddle.net/cu7tn64o/14/

Change value of input with jquery under this class

jQuery:
$('.clickhere').click(function(e){
e.preventDefault();
$(this).closest('.row').children('.abc').hide(); // working
$(this).closest('.row').children('.abc').children('input').value = ''; // not working
$(this).closest('.bookingrow').children('.addressbox').children('input').value(''); // alternative - not working
});
html
<div class="row">
<div class='abc'>
<input type='text' class='unknown' />
</div>
<div class="clickhere">hide</div>
</div>
my target is if i click the "clickhere" class, content under "abc" class will hide and whatever content added by customer on those input box, they will be clear.
same html used multiple time on the same form. that's why using "$(this)".
any solution? what i am doing wrong?
Thanks in advance.
You need to use .val() to set the value, jQuery methods normally will return a jQuery object not a dom element reference so you would not have a properly called .value.
$(this).closest('.row').find('.abc input').val('');
So
$('.clickhere').click(function (e) {
e.preventDefault();
//cache the value of .row since it is used multiple times
var $row = $(this).closest('.row');
$row.children('.abc').hide(); // working
$row.find('.abc input').val('');
});

How to hide a dynamically created element with JS?

I want all the elements with id #text-field to be hidden (if the browser support JS, that's why it should be hidden with JS). But don't get it to work with elements created this way:
// Add post
$(document).on('click', 'a.add-post', function(event)
{
// Create content based on a hidden item
var newcontent = $('.type-post#post_id-hid-0').html();
content = '<li class="type-post">' + newcontent + '</li>';
// Place new content
$('.posts-list > li.iteration-0').last().after(content);
// Load necessary JS
load_page();
event.preventDefault();
});
And my load_page() function:
$(function()
{
function load_page()
{
$('#text-field').hide();
}
load_page();
}
Use a class for text-field instead of an ID, ID's are unique for each element while a class can be used over again for this purpose.
A lightweight solution which doesn't require any JS to execute, and won't cause a 'jumpy' interface when it first loads and elements disappear in front of users eyes.
CSS:
#text-field{display:hidden;}
HTML:
<noscript>#text-field{display:block;}</noscript>
you have to do two things:
function load_page(){ //<----put this in global scope
$('.text-field').hide(); //<---hide it with class name
}
$(function(){
load_page();
});
so now somewhere in your page you might have this <input type='text' id='text-field' /> here you can change your elem's id to class this way:
<input type='text' class='text-field' />
this should help if you can replace classname with whichever dynamic page related class you insert :
$(".classname[id='text-field']").hide();
or
$(".classname[id='text-field']").attr("style", "display:none");

How to get text value in jquery?

I have three elements, which are sliding on the screen, i want to get the text of element which is currently showing on the screen, I tried .text() function, but this returns the text of all the s elements, is there any way using javascript or jquery to do this.
<div id="text">
<span style=" font-size:100px;text-align:center;">koko</span>
<span style=" font-size:100px;text-align:center;">abc</span>
<span style=" font-size:100px;text-align:center;">efh</span>
</div>
$(document).ready(function(){
$('#text').mouseover(function(){
var txt = $('#text span').text();
alert(txt);
});
});
demo or another here
code
$('#text > span').mouseover(function(){
var txt = $(this).text();
alert(txt);
});
Since you are using the cycle plugin, the active slide is given the class "activeSlide". You can get the text of the active slide by doing something like $('.activeSlide').text();
You can also set a callback in the options while initialising the cycle plugin. You can look at the options that you can set with cycle here: http://jquery.malsup.com/cycle/options.html
You will be able to use the "after" event callback in case you want to do something everytime the slide changes.
$(document).ready(function () {
$('#text').cycle({
after: function (currSlideElement, nextSlideElement, options, forwardFlag) {
alert($(nextSlideElement).text());
}
});
});

Categories