Transform input back into a div on button click - javascript

I am using the following code
$(document).on('click', '#editDetailBtn', function () {
var input = $('<input id="#detailprimaryDescription" type="text" />');
input.val($('#detailprimaryDescription').text());
$('#detailprimaryDescription').replaceWith(input);
$('#editDetailBtn').hide();
$('#detailPrimaryCancel').show();
$('#detailPrimarySave').show();
});
$(document).on('click', '#detailPrimaryCancel', function () {
var input = $('<div id="#detailprimaryDescription" ></div>');
//input.val($('#detailprimaryDescription').text());
$('#detailprimaryDescription').replaceWith(input);
$('#editDetailBtn').show();
$('#detailPrimaryCancel').hide();
$('#detailPrimarySave').hide();
});
what I am trying to achieve is to once cancel is clicked then it will turne the input field back into a div
http://jsfiddle.net/7XWAu/

I think this is what you're shooting for.
JS FIDDLE
you don't need to place '#' at the beginning of an id in the dom, its only used to reference elements.
so basically, every where you had something like:
var input = $('<input id="#detailprimaryDescription_input" type="text" />');
you shouuld be doing something like:
var input = $('<input id="detailprimaryDescription_input" type="text" />');
once I cleaned that up it worked as it does in the fiddle.
I do want to say, that it would be a muchhhhhhh better practice to just show and hide a div containing all those inputs rather than manipulating the DOM to create / destroy them constantly.

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

Unable to remove an element from dynamic jquery form

I am creating a dynamic form with a wysiwig editor nice editor which goes like this.
Scripts needed
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://js.nicedit.com/nicEdit-latest.js" type="text/javascript"></script>
<script type="text/javascript">bkLib.onDomLoaded(nicEditors.allTextAreas);</script>
Html
<div id="p_scents">
<p>
<input type="text" name="title">
<textarea name="description[]" rows="20" cols="80"></textarea>
</p>
</div>
And the jquery function
$(function () {
var editors = {}; //Keep track of all added nicEditors for removal later
var scntDiv = $('#p_scents');
$(document).on('click', '#addScnt', function () {
var elm = $('<div class="con"><input type="text" id="Text1" value="" /></div>').appendTo(scntDiv);
var elm = $('<textarea NAME="description[]"></textarea>').appendTo(scntDiv); // Add the textarea to DOM
var curSize = $('textarea[name="description[]"]').length; //Get the current SIZE of textArea
editors[curSize] = new nicEditor().panelInstance(elm[0]); //Set the Object with the index as key and reference for removel
elm.after($('<a/>', { //Create anchor Tag with rel attribute as that of the index of corresponding editor
rel: curSize,
'class': "remScnt",
text: "Remove",
href: '#'
})).next().andSelf().wrapAll($('<p/>')); //add it to DOM and wrap this and the textarea in p
});
$(document).on('click', '.remScnt', function (e) {
e.preventDefault();
var elem = $(this).prev('textarea'); //Get the textarea of the respective anchor
var index = this.rel; //get the key from rel attribute of the anchor
editors[index].removeInstance(elem[0]); //Use it to get the instace and remove
delete editors[index]; //delete the property from object
$(this).closest('con').remove();
$(this).closest('p').remove(); //remove the element.
});
});
This script is taken from this stack overflow question.
NicEdit html editor for managing dynamic add/remove textareas
With this scrip i want to attach a text field as title the above script is creating the same but once it is created if i press on remove button it is not getting removed only the text area is getting removed where am i going wrong how can i fix this?
Updated fiddle is here http://jsfiddle.net/eEUEW/34/
you can use .parent() and .prev()
replace
$(this).closest('con').remove();
$(this).closest('p').remove();
with
$(this).parent().prev().remove();
$(this).closest('p').remove();

jquery/JS simple data bind for dynamic controls

I have on the html page an and elements, created dynamically via js.
<input type="text" id="MyInput" name="MyInput"
class='form-control copyMe' placeholder="enter smth pls"/>
<div id="jsonTextAreaDiv" contenteditable="true">
<span id="MyInput_JSON"></span>
</div>
And I want to have text binding from input to span.
So, I go with next JS:
$(document).on('input', 'input.copyMe', function(){
var valToInsert = $(this).val();
var idToInsert = $(this).attr("id") + "_JSON";
document.getElementById(idToInsert).innerHTML = valToInsert;
});
Could be all in one line jquery, but... Anyway.
This binding works fine during entering text to input.
But once input looses focus - suddenly span looses inner text.
I don't know why. This is exactly my question, how is it happening?
I've "worked around" this issue with adding
$(document).on('input', 'input.copyMe', function(){
var valToInsert = $(this).val();
var idToInsert = $(this).attr("id") + "_JSON";
document.getElementById(idToInsert).innerHTML=valToInsert;
}).on('blur', '.copyMe', function(){
var valToInsert = $(this).val();
var idToInsert = $(this).attr("id") + "_JSON";
document.getElementById(idToInsert).innerHTML=valToInsert;});
This way it works like I want it. But this is ridiculous.
Any ideas regarding why does the value disappear from span at the first place?
Thanks in advance.
Change your input event to use the change event instead. IE does not support the 'input' event correctly. Alternatively, you could try using the keyup event.
$(document).on('change', 'input.copyMe', function(){
var valToInsert = $(this).val();
var idToInsert = "#" + $(this).attr("id") + "_JSON";
$(idToInsert).html(valToInsert);
});
Also, i changed your last line to jQuery as well. There's no reason to mix jQuery and pure JS together. It makes it easier to read if you keep it uniform.

Jquery Remove Element from List

I have a list in JQuery that's called additionalInfo, which is filled in using this JQuery function:
$('#append').on('click', function () {
//check if the following area is valid before moving on, check the jquery validation library
var text = $('#new-email').val();
var li = '<li>' + text + 'input type="hidden" name="additionalInfo" value="'+text+'"/> </li>';
$('#additional-info-list').append(li);
$('#new-email').val('');
});
The point of the function is not only to store the info in a list that can be used later, but also to render a <li> with the info text in it. Right now I have another button on each <li> that when pressed, makes the li vanish, but I also need to add code to it that completely removes the info text from the additionalInfo list. This is the code I have for that method so far:
$('#removeEmail').on('click', 'li>.remove-btn', function (event){
$(event.currentTarget).closest('li').remove();
});
How can I get the segment of info text out of the li and then remove it from additionalInfo?
You have few problems. First of all when you create the new items, your markup is not correct. You were missing the opening bracket of input tag. Also i changed the code for delete so that it listens for the click event on any item with class remove-btn under the li element. This should delete the item when you click the remove link inside the li.
$(function(){
$('#append').on('click', function () {
var text = $('#new-email').val();
var li = '<li>' + text + '<input type="hidden" name="additionalInfo"
value="'+text+'"/>
<a href="#" class="remove-btn" >remove</a></li>';
$('#additional-info-list').append(li);
$('#new-email').val('');
});
$(document).on('click', 'li>.remove-btn', function (event){
var _this =$(this);
_this.closest('li').remove();
});
});
Here is a working jsfiddle

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");

Categories