Js/jQuery - How to hide/show an input created on the fly? - javascript

This code creates a group of elements (four inputs) on the fly. Once you create an element (four inputs) you can select/deselect, when you select an element will bring up the editor for the corresponding element. I've made a function to hide only the first element. The problem is that I can not make it comeback without affecting the other elements.
Instructions:
Click on the "Price" link, an element will be created on the fly (four nested inputs)
Select the element (four nested inputs) to bring up the editor ( one input and a brown little square).
Click on the little brown square to hide the first input of the element (four nested inputs) and that will hide the first input.
I need the little brown square to hide and show the same input.
Go here to see the full code:
To see the problem you have to create more than one element to find out.
http://jsfiddle.net/yjfGx/13/
This is the JS/jQuery code, for the full code go to the link above.
var _PriceID = 1;
$('#Price').on('click',function(){
var label = 'Price'
var Id = 'Price_';
var P = $( '<p class="inputContainer" />' ).fadeIn(100);
var l = $( '<label />' ).attr({'for':Id + _PriceID, 'id':Id + _PriceID, 'class':'priceLb'}).text( label ).after('<br/>');
var l1 = $( '<span class="dollar-sign" />' ).text( '$' ).css({"font-family":"Arial", "color":"#333", "font-weight":"bold"});
var input1 = $( '<input />' ).attr({ 'type':'text', 'name':'', 'class':'inputs',
'maxlength':'3', 'placeholder':'one',
'id':Id + _PriceID, 'class':'pricePh-1' })
.css({ "width":"60px", "paddingLeft":"1.3em", "paddingRight":"0.2em", "margin":"3px" });
var l2 = $( '<span class="priceComma-1" />' ).text( ',' ).css({"font-family":"Arial", "color":"#333", "font-weight":"bold"});
var input2 = $( '<input />' ).attr({ 'type':'text', 'name':'', 'class':'inputs', 'maxlength':'3',
'placeholder':'two', 'id':Id + _PriceID, 'class':'pricePh-2' })
.css({ "width":"68px", "paddingLeft":"0.7em", "paddingRight":"0.2em", "margin":"3px" });
var l3 = $( '<span class="priceComma-2" />' ).text( ',' ).css({"font-family":"Arial", "color":"#333", "font-weight":"bold"});
var input3 = $( '<input />' ).attr({ 'type':'text', 'name':'', 'class':'inputs', 'maxlength':'3',
'placeholder':'three', 'id':Id + _PriceID, 'class':'pricePh-3' })
.css({ "width":"64px", "paddingLeft":"1em", "paddingRight":"0.2em", "margin":"3px" }); var l4 = $( '<span />' ).text( ',' ).css({"font-family":"Arial", "color":"#333", "font-weight":"bold"});
var input4 = $( '<input />' ).attr({ 'type':'text', 'name':'', 'class':'inputs', 'maxlength':'2',
'placeholder':'four', 'id':Id + _PriceID, 'class':'pricePh-4' })
.css({ "width":"37px", "paddingLeft":"0.5em", "paddingRight":"0.2em", "margin":"3px" });
P.append( l, l1, input1, l2, input2, l3, input3, l4, input4);
var D = $( 'form' );
P.on({
mouseenter: function() {
$(this).addClass("pb");
},
mouseleave: function() {
$(this).removeClass("pb");
}
});
P.appendTo(D);
_PriceID++;
});
/*** Select element individually and load editor. ***/
var flag = false;
$("form").on("click", "p", function () {
var cur = $(this).css("background-color");
if (cur == "rgb(255, 255, 255)") {
if (flag == false) {
$(this).css("background-color", "#FDD");
LoadPriceProperties($(this));
flag = true;
}
} else {
$(this).css("background-color", "white");
$('.properties-panel').hide();
flag = false;
}
});
/*** Element editor ***/
var LoadPriceProperties = function (obj) {
$('.properties-panel').css('display', 'none');
$('#priceProps-edt').css('display', 'block');
var label = $('.priceLb', obj);
var price1 = $('.pricePh-1', obj);
var price2 = $('.pricePh-2', obj);
$('#SetPricePlaceholder-1').val(price1.attr('placeholder'));
$('#SetPricePlaceholder-2').val(price2.attr('placeholder'));
/*** Getting an answer, depending on what they click on. ***/
$('#fieldOptionsContainer_1 div').bind('click', function () {
if ($(this).hasClass('field-option-delete')) {
RemoveUnwantedPriceField1($(this));
} else {
/*** Function loacated on "line 98" ***/
HideUnwantedPriceField_1($(this));
}
});
_CurrentElement = obj;
};
function HideUnwantedPriceField_1() {
var input = $('.pricePh-1', _CurrentElement);
var comma = $('.priceComma-1', _CurrentElement);
if($(input).is(":hidden")){
} else {
input.hide();
comma.hide();
}
}

Do you mean something like this: http://jsfiddle.net/Zaf8M/
var items=$('.m>li'), set= $('.set input'), num=0, item=$('.item'), list=$('.list');
item.hide();
items.click(function(){
$(this).addClass('sel').siblings().removeClass('sel');
num=$(this).index()+1;
set.prop( "disabled", false );
});
$('.close').click(function(){alert(3);});
$(window).click(function(e){
if( e.target.className=='sel' || e.target.type=='text'){return;}
else {
items.removeClass('sel'); set.prop( "disabled", true );
}
if(set.val()!='') {
item.clone().show()
.appendTo(list).children('.n').text(num)
.siblings('.p').text(set.val());
set.val('');
}
if( e.target.className=='close' ){$(e.target).parent().remove();};
});

Related

Uncaught SyntaxError: Invalid or unexpected token on Inline JS. JS script breaks on browser

I am facing an issue that has baffled and actually exhausted me for hours.
I have tried so many different things, have done and still doing various debugging techniques but I am very tired and would seek for some help of any kind.
I will post the very basics for start, in case someone has any helpful idea/suggestion to unstack me, and I might be adding further information or more code as we go if needed.
I am working on a Joomla site and on a custom component view I place an inline jQuery script at some point of my html output.
The problem is that while everything works well on my localhost, when I upload it online the javascript breaks in whatever point I try to create variables that contain html. Then the browser will auto-close the script tag with </script> and the rest of the js code will be output as html.
So for example, the following script:
<script>
(function($)
{
$(document).ready(function()
{
var loader = '<div id="loader"><div>';
});
})(jQuery);
</script>
will end up to something like below:
<script>
(function($)
{
$(document).ready(function()
{
var loader = '<div id="loader">';
</div></script>
});
})(jQuery);
</script>
*Another clue that I just got is that the issue seems to be when I upload this on Litespeed server.
I tested this on 2 different servers with Litespeed and then on 1 Apache.
The one on the Apache server works fine (like on my localhost).
This is my complete inline script, just in case anyone is in place to catch anything that I am missing.
(function($)
{
$(document).ready(function()
{
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
var obj = <?php echo json_encode($availableTags); ?>;
var searchForm = $('#adminForm');
var predefinedTags = $('.tags-cloud.popular-tags .li-item');
var searchTermId = '';
var oldSearchTermId = '';
var categories = <?php echo json_encode( $search_categories ); ?>;
var categoriesAction = '<?php echo (int)$sel_categories_option; ?>';
var list_limit = '<?php echo (int)$list_limit; ?>';
var list_limitstart = 0;
var list_order_by = '<?php echo $list_order_by; ?>';
var list_order_dir = '<?php echo $list_order_dir; ?>';
var menuItem = '<?php echo (int)$menuItem; ?>';
var show_image = '<?php echo (int)$show_image; ?>';
var show_date = '<?php echo (int)$show_date; ?>';
var which_date = '<?php echo $which_date; ?>';
var show_category = '<?php echo (int)$show_category; ?>';
var searchResults;
var loadMore = false;
var loader = "";
// Form submit
$(searchForm).on('submit', function(e) {
searchTermId = $('#sm-search-term-id').val();
e.preventDefault();
ajaxSearchArticles();
});
$('.search-order-selects').on('change', function(e) {
searchTermId = $('#sm-search-term-id').val();
list_order_by = $('#search-order').val();
list_order_dir = $('#search-order-dir').val();
list_limitstart = 0;
ajaxSearchArticles();
});
$(predefinedTags).on('click', function(e) {
searchTermId = $(this).attr('data-tagid');
$( "#sm-search" ).val( $(this).text() );
$( "#sm-search-term-id" ).val( searchTermId );
$( "#sm-search-description" ).html( '(' + $(this).attr('total_articles') + ' Total Articles)');
ajaxSearchArticles();
return false;
});
$('#search-results').on('click','#load-more-div', function() {
searchTermId = $('#sm-search-term-id').val();
list_limitstart = parseInt(list_limitstart) + parseInt(list_limit);
loadMore = true;
ajaxSearchArticles();
});
function appendResults() {
var html = '';
oldSearchTermId = searchTermId;
var l = parseInt(list_limit);
$(searchResults).each(function(i, e) {
var itemi = list_limitstart + i;
if (i < l) {
html += '<div id="artid-'+e.id+'" class="sm-search-result g-block s-item-'+itemi+'">';
html += '<div class="sm-search-result-content">';
if (show_image == '1') {
html += '<a href="'+ e.url +'" title="'+e.title+'" target="_blank">';
html += '<div class="smrc-image-holder"><img src="' + e.images + '" alt="'+e.title+'" /></div></a>';
}
html += '<div class="smrc-text-block"><h3>'+e.title+'</h3><p>'+e.introtext+'</p>';
if (show_date || show_category) {
html += '<div class="item-meta">';
if (show_date) {
var date = e.modified;
if (which_date === 'created') {
var date = e.created;
}
html += '<span class="item-date"><i class="fa fa-calendar-o" aria-hidden="true"></i> '+ date +'</span>';
}
if (show_category) {
html += '<span class="item-cat">in '+e.category +'</span>';
}
html += '</div>';
}
html += '</div></div></div>';
}
if (i === l) {
html += '<div id="load-more-div" class="sm-search-result load-more g-block">';
html += '<div class="sm-search-result-content" style="display: flex;align-items: flex-end;justify-content: center;height: 100%;">';
html += '<div class="load-more-results flex-item"><span>Load More...</span></div>';
html += '</div></div>';
}
});
html += '<div class="clear clearfix"></div>';
if (loadMore) {
$('#search-results').append(html);
} else {
$('#search-results').html(html);
}
loadMore = false;
}
// Autocomplete
$( function() {
var results = true;
$( "#sm-search" ).autocomplete({
minLength: 3,
source: obj,
focus: function( event, ui ) {
if (results) {
$( "#sm-search" ).val( ui.item.label );
}
event.preventDefault();
return false;
},
select: function( event, ui ) {
if (results) {
$( "#sm-search" ).val( ui.item.label );
$( "#sm-search-term-id" ).val( ui.item.value );
$( "#sm-search-description" ).html( '(' + ui.item.total_articles + ' Total Articles)');
}
event.preventDefault();
$(searchForm).submit();
return false;
},
response: function(event, ui) {
if (ui.content.length === 0) {
results = false;
var res = { label: "no results", value: 0 };
ui.content.push(res);
} else {
results = true;
}
}
}).autocomplete( "instance" )._renderItem = function( ul, item ) {
if (results) {
return $( "<li>" )
.append( "<div><strong>" + capitalizeFirstLetter(item.label) + "</strong> <small>(" + item.total_articles + " articles)</small></div>" )
.appendTo( ul );
} else {
return $( "<li>" )
.append( "<div>" + item.label + "</div>" )
.appendTo( ul );
}
};
});
// Ajax call
function ajaxSearchArticles() {
if (!searchTermId) {
$('#empty-message').text('No Tags Defined!');
setTimeout(function() {
$('#empty-message').text('');
}, 3000);
return false;
}
$('body').append(loader);
if (searchTermId !== oldSearchTermId) {
list_limitstart = 0;
}
var xhrRequest = {
'option' : 'com_rabattdatabase',
'task' : 'RabattAjax.ajaxReceiver',
'action' : 'customSearch',
'tagid' : searchTermId,
'orderby' : list_order_by,
'orderdir': list_order_dir,
'limit' : list_limit,
'limitstart' : list_limitstart,
'cats' : categories,
'itemid' : menuItem,
'catswhat': categoriesAction,
'<?php echo JSession::getFormToken();?>' : 1,
};
$.ajax({
context : this,
type : 'POST',
data : xhrRequest,
success : function(response) {
var response = $.parseJSON(response);
searchResults = response.data;
if (response.success == true) {
appendResults();
} else {
$('#search-results').html("<h4>We couldn't process your request!</h4>");
}
}
}); // End Ajax
}
})
})(jQuery);

How i can put unique value in each box?

How can I put unique value in each box?
I will put a link with example below.
Example: user click on +, a modal appears.
He selects a value from the select and submits.
Then the selected value is printed in that box where user pressed on +.
https://codepen.io/anon/pen/rmbWdY
$(document).ready(function() {
$( ".pat" ).append( $( "<span class='glyphicon glyphicon-plus' aria-hidden='true' data-toggle='modal' data-target='#myModal'></span>"));
$result = $('#result p');
$("#btnsubmit").click(function() {
$(".bl1 .glyphicon").hide();
var text = $("#sel1 option:selected").text();
$result.text(text);
});
$("input[type='radio']").change(function() {
if ($(this).val() == 90) {
$result.removeClass('r45').addClass('r90');
} else {
$result.removeClass('r90').addClass('r45');
}
});
});
function readURL(event){
var getImagePath = URL.createObjectURL(event.target.files[0]);
$('.bg').css('background-image', 'url(' + getImagePath + ')');
}
I played a little with your strange grid.
To have unique numbers in each boxes, you have to remove the selected number and replace it with another.
Math functions are handy for it.
Note that the number are not really unique in this solution... They are random.
Then, to place the number in the right box, I added a .glyphicon (+ sign) click handler to get the element reference.
In this handler, I create a span to replace the + sign... In order to prepare an element, which can be rotated, to receive the selected number.
I added "horizontal" in the radio choices... checked by default.
So here is the code:
CodePen
$(document).ready(function() {
var clickedPlus;
$(document).on("click",".glyphicon",function(){
clickedPlus = $(this).closest("div");
var newSpan = $("<span>");
clickedPlus.html(newSpan);
});
// When modal is close without submit
$(".close").on("click",function(){
clickedPlus.html( $( "<span class='glyphicon glyphicon-plus' aria-hidden='true' data-toggle='modal' data-target='#myModal'></span>") );
});
$( ".pat" ).append( $( "<span class='glyphicon glyphicon-plus' aria-hidden='true' data-toggle='modal' data-target='#myModal'></span>"));
$result = $('#result p');
$("#btnsubmit").click(function() {
$(".bl1 .glyphicon").hide();
var text = $("#sel1 option:selected").text();
$("#sel1 option:selected").text(Math.round(Math.random()*10000));
//$result.text(text);
clickedPlus.find("span").text(text);
});
$("input[type='radio']").change(function() {
if ($(this).val() == 90) {
//$result.removeClass('r45').addClass('r90');
clickedPlus.find("span").removeClass('r45').addClass('r90');
} else if ($(this).val() == 45) {
//$result.removeClass('r90').addClass('r45');
clickedPlus.find("span").removeClass('r90').addClass('r45');
} else{
clickedPlus.find("span").removeClass('r90').removeClass('r45');
}
});
}); // ready
function readURL(event){
var getImagePath = URL.createObjectURL(event.target.files[0]);
$('.bg').css('background-image', 'url(' + getImagePath + ')');
}
Get the element position in the list and append to that element the value
$(document).ready(function() {
$(".pat").append($("<span class='glyphicon glyphicon-plus' ></span><span class='text'></span>"));//add a span with the class .text
$(".pat:not(.bl1)").click(function() {
var ind = $(this).index();//get the column position
var vind = $(this).parent().attr('class'); get the row class
$('#myModal').attr('data-ind', ind).attr('data-vind', vind).modal('show');//pass the values to the modal window
})
$result = $('#result p');
$("#btnsubmit").click(function() {
var ind = $(this).closest('.modal').attr('data-ind');//get the values
var vind = $(this).closest('.modal').attr('data-vind');
var text = $("#sel1 option:selected").text();
$result = $('.' + vind).find('.pat').eq(ind);//select the right element from the list
$result.find(".glyphicon").hide();
$result.find('.text').text(text);
});
$("input[type='radio']").change(function() {
var ind = $(this).closest(".modal").attr("data-ind");
var vind = $(this).closest(".modal").attr("data-vind");
$result = $("." + vind).find(".pat").eq(ind);
if ($(this).val() == 90) {
$result.find('.text').removeClass("r45").addClass("r90");
} else {
$result.find('.text').removeClass("r90").addClass("r45");
}
});
});
function readURL(event) {
var getImagePath = URL.createObjectURL(event.target.files[0]);
$('.bg').css('background-image', 'url(' + getImagePath + ')');
}
demo:https://codepen.io/anon/pen/EmJZrY

VB.net non MVC RAZOR | Need help, javascript stack procress

I make a shopping website and have 2 menu, when i call page from ajax to show on my content zone (On DIV).
<script>
$(function () {
$("#chicken_tab2").click(function () {
$.ajax({
type: "POST",
url: "/view/Content/Index_cp.vbhtml",
datatype: "html",
success: function (data) {
$("#getcontent").html(data);
}
});
});
});
</script>
My content come to show but it can't use javascipt from _Layout.vbtml.
Then i put Main.js(it's Cart jquery)
<script src="~/view/Cart/main.js"></script>
inside main.js
jQuery(document).ready(function ($) {
//var getnum = $('#getnum').val();
//alert(getnum);
var cartWrapper = $('.cd-cart-container');
//product id - you don't need a counter in your real project but you can use your real product id
var productId = 0;
if( cartWrapper.length > 0 ) {
//store jQuery objects
var cartBody = cartWrapper.find('.body')
var cartList = cartBody.find('ul').eq(0);
var cartTotal = cartWrapper.find('.checkout').find('span');
var cartTrigger = cartWrapper.children('.cd-cart-trigger');
var cartCount = cartTrigger.children('.count')
var addToCartBtn = $('.cd-add-to-cart');
var undo = cartWrapper.find('.undo');
var undoTimeoutId;
var getnum = $('.getnum');
//-----------------------------------------------------------------------------------------------------
//O function Strat
//O function End
//add product to cart
addToCartBtn.on('click', function(event){
event.preventDefault();
addToCart($(this));
});
//open/close cart
cartTrigger.on('click', function(event){
event.preventDefault();
toggleCart();
});
//close cart when clicking on the .cd-cart-container::before (bg layer)
cartWrapper.on('click', function(event){
if( $(event.target).is($(this)) ) toggleCart(true);
});
//delete an item from the cart
cartList.on('click', '.delete-item', function(event){
event.preventDefault();
removeProduct($(event.target).parents('.product'));
});
//update item quantity
cartList.on('change', 'select', function(event){
quickUpdateCart();
});
//reinsert item deleted from the cart
//undo.on('click', 'a', function(event){
// clearInterval(undoTimeoutId);
// event.preventDefault();
// cartList.find('.deleted').addClass('undo-deleted').one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(){
// $(this).off('webkitAnimationEnd oanimationend msAnimationEnd animationend').removeClass('deleted undo-deleted').removeAttr('style');
// quickUpdateCart();
// });
// undo.removeClass('visible');
//});
}
function toggleCart(bool) {
var cartIsOpen = ( typeof bool === 'undefined' ) ? cartWrapper.hasClass('cart-open') : bool;
if( cartIsOpen ) {
cartWrapper.removeClass('cart-open');
//reset undo
clearInterval(undoTimeoutId);
undo.removeClass('visible');
cartList.find('.deleted').remove();
setTimeout(function(){
cartBody.scrollTop(0);
//check if cart empty to hide it
if( Number(cartCount.find('li').eq(0).text()) === 0) cartWrapper.addClass('empty');
}, 500);
} else {
cartWrapper.addClass('cart-open');
}
}
function addToCart(trigger) {
var ids = trigger.data('ids');
var item = trigger.data('item');
var cartIsEmpty = cartWrapper.hasClass('empty');
//update cart product list ****add trigger in ()
addProduct(trigger.data('item'),trigger.data('detail'), trigger.data('productname'), trigger.data('pic'), $('#' + ids + '').val());
//update number of items
updateCartCount(cartIsEmpty);
//update total price
updateCartTotal(1, true);
//show cart
cartWrapper.removeClass('empty');
}
function commaSeparateNumber(val) {
while (/(\d+)(\d{3})/.test(val.toString())) {
val = val.toString().replace(/(\d+)(\d{3})/, '$1' + ',' + '$2');
}
return val;
}
function addProduct(item, detail, product, pic, QTY) {
//this is just a product placeholder
//you should insert an item with the selected product info
//replace productId, productName, price and url with your real product info
productId = productId + 1;
//var productAdded = $('<li class="product"><div class="product-image"><img src="Cart/product-preview.png" alt="placeholder"></div><div class="product-details"><h3>'+ product +'</h3><span class="price">$'+ 1 +'</span><div class="actions">Delete<div class="quantity"><label for="cd-product-'+ productId +'">Qty</label><span class="select"><select id="cd-product-'+ productId +'" name="quantity"><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option></select></span></div></div></div></li>');
var productAdded = $('<li class="product"><div class="product-image"><input type="text" name="item" value="' + item + '" hidden /><input type="text" name="detail" value="' + detail + '" hidden /><img src="/view/images/' + pic + '" alt="placeholder"></div><div class="product-details"><h3>' + product + '</h3><input type="text" name="productname" value="' + product + '" hidden /><input type="text" name="pic" value="/view/images/' + pic + '" hidden /><span class="price">จำนวน</span><span class="price">' + QTY + ' kg.</span><input class="price" type="text" hidden name="QTY" value="' + QTY + '"><div class="actions">ลบ</div></div></li>');
cartList.prepend(productAdded);
}
function removeProduct(product) {
clearInterval(undoTimeoutId);
cartList.find('.deleted').remove();
var topPosition = product.offset().top - cartBody.children('ul').offset().top ,
productQuantity = Number(product.find('.quantity').find('select').val()),
productTotPrice = Number(product.find('.price').text().replace('$', '')) * productQuantity;
product.css('top', topPosition+'px').addClass('deleted');
//update items count + total price
updateCartTotal(1, false);
updateCartCount(true, -productQuantity);
undo.addClass('visible');
//wait 8sec before completely remove the item
undoTimeoutId = setTimeout(function(){
undo.removeClass('visible');
cartList.find('.deleted').remove();
}, 0);
}
function quickUpdateCart() {
var quantity = 0;
var price = 0;
cartList.children('li:not(.deleted)').each(function(){
var singleQuantity = Number($(this).find('select').val());
quantity = quantity + singleQuantity;
price = price + singleQuantity*Number($(this).find('.price').text().replace('$', ''));
});
cartTotal.text(price.toFixed(2));
cartCount.find('li').eq(0).text(quantity);
cartCount.find('li').eq(1).text(quantity+1);
}
function updateCartCount(emptyCart, quantity) {
if( typeof quantity === 'undefined' ) {
var actual = Number(cartCount.find('li').eq(0).text()) + 1 ;
var next = actual + 1;
if( emptyCart ) {
cartCount.find('li').eq(0).text(actual);
cartCount.find('li').eq(1).text(next);
} else {
cartCount.addClass('update-count');
setTimeout(function() {
cartCount.find('li').eq(0).text(actual);
}, 150);
setTimeout(function() {
cartCount.removeClass('update-count');
}, 200);
setTimeout(function() {
cartCount.find('li').eq(1).text(next);
}, 230);
}
} else {
var actual = Number(cartCount.find('li').eq(0).text()) -1 ;
var next = actual + 1;
cartCount.find('li').eq(0).text(actual);
cartCount.find('li').eq(1).text(next);
}
}
function updateCartTotal(price, bool) {
bool ? cartTotal.text( (Number(cartTotal.text()) + Number(price)).toFixed(0) ) : cartTotal.text( (Number(cartTotal.text()) - Number(price)).toFixed(0) );
}
});
and when i change back to this page it stack a function (one time come back to this page it will do 2 time function and more if you come back again) I must to say sorry my English is not good and so thank you for help.

Cannot select a button which appended dynamically in jQuery

I use getJSON function in jQuery and append the retrieved result in the form of button in the DOM. however I cannot use the selector on the appended DOM.
here is my script:
$.getJSON("http://example.com/checkDiary.php?babyID=" + localStorage.getItem("babyRegNo"), function(data) {
if (data.indexOf("noDiary") > -1) {
document.getElementById("diaryList").innerHTML = "<p>Your baby currently has no diary entry.</p>";
} else {
var appendedText = '';
$.each(data, function(){
var diaryID = this.diary_id;
var dateAdded = this.date;
appendedText = appendedText + '<p><button type="button" class="diaries" value ="' + diaryID + '">' + dateAdded + '</button></p>';
})
document.getElementById("diaryList").innerHTML = appendedText;
}
})
this is what i use to select:
$(':button.diaries').click(function(){});
but it seems not working. however when I put a dummy button with the same class in the HTML body, it is selected perfectly. Can you guys give me any suggestion?
#Kelvin Aliyanto ....So the solution will be like this
<script src="jquery-1.7.2.min.js" type="text/javascript"></script>
<script>
$(function(){
$.getJSON("http://example.com/checkDiary.php?babyID=" + localStorage.getItem("babyRegNo"), function(data) {
if (data.indexOf("noDiary") > -1) {
document.getElementById("diaryList").innerHTML = "<p>Your baby currently has no diary entry.</p>";
} else {
var appendedText = '';
$.each(data, function(){
var diaryID = this.diary_id;
var dateAdded = this.date;
appendedText = appendedText + '<p><button type="button" class="diaries" value ="' + diaryID + '">' + dateAdded + '</button></p>';
})
document.getElementById("diaryList").innerHTML = appendedText;
}
});
$('div').on('click', '.diaries', function(event){
alert("Hi");
}) ;
});
</script>
<div id="diaryList"></div>
check your code is after document ready
$(document).ready(function(){ //your code here });
and use
$('button.diaries').on(click , function(){})
instead of .click

How to get the values of all textfields in add/remove textfields and form JSON

I'm using a plugin to duplicate textfields on add and remove buttons. Now, after getting the fields added and removed, I want to form JSON out of all the textfields and POST it on submit.
Below is the code -
$(function () {
var scntDiv = $('#p_scents');
var i = $('#p_scents p').size() + 1;
$('#addScnt').live('click', function () {
$('<p><label for="p_scnts"><input type="text" id="p_scnt_' + i + '" size="20" name="p_scnt_' + i + '" value="" placeholder="Input Value" /></label> Remove</p>').appendTo(scntDiv);
i++;
return false;
});
$('#remScnt').live('click', function () {
if (i > 2) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
JSFiddle can be referred to.
I want to get the values of all textfields and form JSON.
Iterate through the input fields, grab their values, and push them through JSON.stringify to create your desired JSON.
function serializeAndPost() {
var values = [];
$( '#p_scents input[id^=p_scnt_]' ).each( function ( index, element ) {
values.push( element.value );
} );
var json = JSON.stringify( { "welcomesList": values } );
// Do your POSTing here
}
Updated fiddle:
https://jsfiddle.net/tZPg4/11019/
I don't know if this is the best solution as I am building a string rather than an JSON object but here is my solution:
HTML
<input type="button" id="btnSubmit" value="Submit"></input>
JS:
$(function () {
var scntDiv = $('#p_scents');
var i = $('#p_scents p').size() + 1;
$('#addScnt').live('click', function () {
$('<p><label for="p_scnts"><input type="text" id="p_scnt_' + i + '" size="20" name="p_scnt_' + i + '" value="" placeholder="Input Value" /></label> Remove</p>').appendTo(scntDiv);
i++;
return false;
});
$('#remScnt').live('click', function () {
if (i > 2) {
$(this).parents('p').remove();
i--;
}
return false;
});
$('#btnSubmit').click(function(e) {
e.preventDefault();
var str = [];
$.each($('input[type=text]'), function(i, val) {
var el = $(this);
str.push('"' + el.attr("id") + '":"' + el.val() +'"');
});
var json_string = "{" + str + "}";
});
});

Categories

Resources