replace a <p> element with an input element - javascript

I have a p element which I want to replace with an input element when user clicks on it. The might not be present during page load so I use delegate to catch the click event.
html(after <p> was loaded)
<div class="phrases">
<div class="predefined-phrase>
<p id="1">A predefined phrase"</p>
</div>
</div>
I want it to be like this
<div class="phrases">
<div class="predefined-phrase">
<input type="text" id="1" class="form-control input-sm" value="A predefined phrase">
</div>
</div>
My js file has the following code:
$(".phrases").on('click', ".predefined-phrase", function (event){
event.preventDefault();
var phrase = $(this).children().text();
var id = $(this).children().attr('id');
var input = '<input type="text" class="form-control input-sm" id="'+id+'" value="'+phrase+'">';
$(this).children().remove();
$(this).append(input);
});
<p> is replaced normally by input but i cannot type anything. I can only type if left click is pressed on input box continiously. I also want to catch a keypress event on the new input so to edit or to delete the specific phrase. But I cannot even type on the input box. Why is this happening? Can i normally catch the keypress event after I have appended the input (and works as it should) inside the click event callback? The point is that after user presses the phrase is edited with ajax and the input box dissappears and p is loaded back with the new edited phrase or fully deleted.

$(function(){
$('.predefined-phrase p').click(function() {
var id = $(this).attr('id');
var phrase = $(this).text();
var newInput="<input type='text' id='"+id+"' value='"+phrase+"' />";
$(this).replaceWith(newInput);
});
});
DEMO FIDDLE

Just check the target. If it is a input, do nothing :
$(".phrases").on('click', ".predefined-phrase", function (event){
if($(event.target).is('input')) return;
event.preventDefault();
var phrase = $(this).children().text();
var id = $(this).children().attr('id');
var input = '<input type="text" class="form-control input-sm" id="'+id+'" value="'+phrase+'">';
$(this).children().remove();
$(this).append(input);
});

Well, this is a native JS solution, but hopefully it will point you in the right direction, or if you an use it instead of jQuery, that works too. Not that I've changed your ID to not start with a number, as mentioned by C-link, as that is not allowed.
document.getElementById("n1").addEventListener("click", function filler(){
this.outerHTML = '<input type="text" id="' + this.id + '" class="form-control input-sm" value="' + this.innerHTML + '" />
this.removeEventListener("click" filler)'
});

I would suggest the next changes:
<div class="predefined-phrase">
<input type="text" data-id="1" class="form-control input-sm" value="A predefined phrase">
</div>
jQuery script:
$('.predefined-phrase').click(function() {
var id = $('p', this).attr('data-id');
var value = $('p', this).text();
$('p', this).replaceWith('<input type="text" data-id="' + id + '" class="form-control input-sm" value="' + value + '" />')
});

First of all, don't use id starting from number.
And for your solution you can use replaceWith method like below:
$('#your_id').replaceWith('<input type="text" id="your_id" class="form-control input-sm" value="A predefined phrase" />');

Related

Get value of an input field after input by user with Event listener using embedded script tag

I am trying to change the value of a placeholder attribute tag based on a value entered by a user in a user input field.
I have tried embedding script tags in the html string I am serving/loading to the page in order to use an eventListener to target the id and store the new value in a variable that is declared outside of the tags in my html string.
Here is the code I am experimenting with:
// Endpoint Resource
"<strong>Endpoint Resource</strong>" +
"<script>" +
"document.getElementById(\"inputTokenRequestorID\").addEventListener(\"change\", function(event){" +
"tokenRequestorID = event.target.value;" +
"});" +
"uri = \"/vtis/tokenRequestors/\" + tokenRequestorID;" +
"</script>" +
"<div class=\"form-group\">" +
"<label for=\"eventID\">Resource</label>" +
"<input class=\"form-control mx-sm-3 resource\" type=\"text\" placeholder=" + uri + " readonly>" +
"<small id=\"InlineHelp\" class=\"text-muted\">" +
//"GUID Type used for tracking." +
"</small>" +
"</div>"
How do I capture the value of an input field after a user enters the data into the field, store it in a variable declared outside of the script tag, and then put its value as another input fields placeholder value?
Thanks.
The basic idea is this:
<script>
function change() {
var input = document.getElementById('userInput').value;
document.getElementById('myInput').placeholder = input;
}
</script>
<input type="text" id="userInput" placeholder="Enter something here.">
<p>
Replaced Placeholder:
</p>
<input type="text" id="myInput" placeholder="Watch me change">
<p>
<button onclick="change()">Change Placeholder</button>
</p>
https://jsfiddle.net/gugui3z24/ceomk9xb/
Or if you want something more dynamic:
<input type="text" id="userInput" placeholder="Enter something here.">
<p>
Replaced Placeholder:
</p>
<input type="text" id="myInput" placeholder="Watch me change">
<script>
document.getElementById('userInput').addEventListener('input', function() {
var input = document.getElementById('userInput').value;
document.getElementById('myInput').placeholder = input;
});
</script>
https://jsfiddle.net/gugui3z24/ceomk9xb/1/

Prevent reload page with code added afterwards and after clicking a button

first of all I'm trying to create a form where is needed to duplicate some blocks of fields and fields as the user want.
So I have a page where there is a button that after clicking on it duplicates a certain block. The first button works fine!, it duplicates a block without reloading the page when is clicked.
But in that block there are some input fields that I need to duplicate as well.
So when the block is duplicated a new button is added to duplicate fields inside that block.
The problem is that when I click on the second button it reloads the page, instead of just duplicate an input field.
To do this I'm using jquery, code to duplicate the block, this is the code to add the block, that is working fine:
$('#add-block').click(function(e) {
var html_to_add = '<input type="text" placeholder="Your Test" class="form-control" name="we2_test" id="we2_test">';
html_to_add += '<div class="we2_test-input col-md-12 no-pad"></div>';
html_to_add += '<button class="btn btn-default btn-add-test" id="we2_add_test">+</button>';
$(".block-input").append(html_to_add);
event.preventDefault();
});
code to duplicate the field (here is where the page reloads):
$('#we2_add_test').click(function(e) {
event.preventDefault();
$(".we2_test-input").append("<input type=\"text\" placeholder=\"Your Test\" class=\"form-control\" name=\"we3_test\" id=\"we3_test\">");
return false;
});
I already tried this, but it didn't work
1.id="we2_test" need to be class="we2_test" and id=we2_add_test need to be class="we2_add_test",because multiple same id for different HTML element is wrong when you are going to deal them with jQuery
2.Use event delegation:-
Now both code need to be:-
$('#add-block').click(function(e) {
e.preventDefault();
var html_to_add = '<input type="text" placeholder="Your Test we2_test" class="form-control" name="we2_test">';
html_to_add += '<div class="we2_test-input col-md-12 no-pad"></div>';
html_to_add += '<button class="btn btn-default btn-add-test we2_add_test">+</button>';
$(".block-input").append(html_to_add);
});
$(document).on('click','.we2_add_test',function(e) {
e.preventDefault();
$(".we2_test-input").append("<input type='text' placeholder='Your Test' class='form-control we3_test' name='we3_test'>");
});
The first function has event as the function argument, but later on you try to use e.preventDefault(). That doesn't match.
Maybe
$('#add-block').click(function(e) {
var html_to_add = '<input type="text" placeholder="Your Test" class="form-control" name="we2_test" id="we2_test">';
html_to_add += '<div class="we2_test-input col-md-12 no-pad"></div>';
html_to_add += '<button class="btn btn-default btn-add-test" id="we2_add_test">+</button>';
$(".block-input").append(html_to_add);
e.preventDefault();
});
will work? Difficult to say without the complete code though ...
Below is a somehow working version...
This is a little working snippet where I took care of the identity problem and the event delegation as mentioned/solved by #Alive to Die:
$(function(){
$('#add-block').click(function(e) {
var i=$('[name=we2_test]',".block-input").length;
var html_to_add = '<input type="text" placeholder="Your Test" class="form-control" name="we2_test" id="we2_test'+i+'">'
+'<div class="we2_test-input col-md-12 no-pad"></div>'
+'<button class="btn btn-default btn-add-test" id="we2_add_test">+</button>';
$(".block-input").append(html_to_add);
e.stopPropagation();
return false;
});
$('.block-input')
.on('click','#we2_add_test',function(e) {
e.preventDefault();
var j=$('[name=we3_test]',".we2_test-input").length;
$(this).prev().append('<input type="text" placeholder="Your Test" class="form-control" name="we3_test" id="we3_test'+j+'">');
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
add block
<div class="block-input"></div>
Edit:
I replaced $(".we2_test-input").append(...) by $(this).prev().append(...) to ensure that only the div before the button gets added to.

id + 1 on append, responsive filemanager multiple select image

still looking for code, how can i have different id on input attribute each time i click add button, I have no idea on how to make the id unique ,please help me..
$(document).ready(function(){
$("#btn2").click(function(e){
e.preventDefault();
var id = $(".inputclass").attr("id");
var newid = parseInt(id) + 1;
$('.inputclass').attr("id", ""+newid+"");
$("#gallery").append(
'<div class="added">'
+'<div class="col-md-2">'
+'<div>'
+'<a class="fileman" href="#"" data-toggle="modal" data-target="#FileManager">'
+'<img id="1" class="imageview center-block" src="/assets/img/noimage150x150.png"></a>'
+'</div>'
+'<a class="tutup btn btn-sm btn-warning">delete<a>'
+'<input class="inputclass" name="image" type="text" value="" class="form-control" id="1"/>'
+'</div>'
+'</div>'
);
});
$("#gallery").on('click', '.tutup', function(e) {
e.preventDefault();
$(this).parent().remove();
});
});
Here you go. You just need to insert id when you generate html
+'<input class="otherClass" name="image" type="text" value="" class="form-control" id="'+newid+'"/>'
Also you need to change class name of input.
https://jsbin.com/pinegowotu/1/edit?html,console,output
Fix bin
Hope this helps.

Dynamically remove a dynamically added input (type=file)

I have a form where user can add files to be uploaded. Change event on that input adds new input the same type and so on. But the new inputs have to have "X" character with click event attached to it to be able to remove the input field and the X chracter.
The form:
<form id="upload_form">
<div class="p_file">
<p class="icon">X</p>
<input type="file" name="userfile1" size="40" class="required" />
</div>
</form>
and the JavaScript:
$('#upload_form input[type="file"]').change(function(){
addUploadField($(this));
});
function addUploadField($field)
{
$current_count = $('#upload_form input[type="file"]').length
$next_count = $current_count + 1;
$field.parent('p').after('
<div class="p_file" >
<p class="icon">X</p>
<input type="file" name="userfile'+$next_count+'" size="40" />
</div>
');
$field.unbind('change');
$nextField = $('#upload_form input[type="file"]').last();
$nextField.bind('change',function(){
addUploadField($(this));
});
$("#upload_form .icon").on('click',function(){
removeUploadField($field);
});
}
function removeUploadField($field)
{
$field.parent('p').remove();
}
The code above remove all the fields after the clicked 'X' character. What I want to do is to remove only the next input field.
I tried to prepare this example in jsFiddle, but I can't make this work. Anyhow maybe this would help.
Putting "div" tag inside "p" tag is the main problem
Remove is corrected in this code
Note: In your html code "div" is is added inside "p" tag, this is invalid practice
HTML:
<form id="upload_form">
<div class="p_file">
<div class="icon">X</div>
<input type="file" name="userfile1" size="40" class="required" />
</div>
</form>
Script:
$('body')
.delegate('#upload_form input[type="file"]', 'change', inputChanged)
.delegate('#upload_form .icon', 'click', removeField);
function inputChanged() {
$current_count = $('#upload_form input[type="file"]').length;
$next_count = $current_count + 1;
$(this).closest('.p_file').after(
'<div class="p_file" ><div class="icon">X</div>' +
'<input type="file" name="userfile'
+ $next_count + '" size="40" /></div>');
}
function removeField(){
$(this).closest('.p_file').remove();
return false;
}
Link: http://jsfiddle.net/cBrQX/2/

programatically change textbox type from type='text' to type='password'

i have username and password textboxes. i want them to both show the default text, ie "username" and "password", but when the user clicks on the password box it should dynamically change to a "password" type for security reasons.
i've managed to do this easily enough with javascript code but it doesn't want to work in IE.
<input id="username" class="username" name="u" type="text" value="username" onclick="if(this.value='username') {this.value=''};" />
<input id="password" class="password" name="p" type="text" value="password" onclick="if(this.value='password') {this.value=''; this.type='password'};" />
Let say your html code is like this
<input type="text" id="txtId" />
you can replace it by using Jquery,
$('#txtId').replaceWith('<input type="password" id="txtId" />')
IE only lets you set the type of an input element once, when the element is created. Attempts to set it after that will fail.
If you want to "change" the element in IE, what you'll likely need to do is create another element with the same attributes (except for the type, of course), and replace the existing element with it.
Or create a dummy textbox for the password, and have the real password box hidden -- on focus the dummy box should hide itself, and show and focus on the real password box.
Would you consider using JQuery?
$("[name=fieldname]").attr("type", "password");
Here is a function to replace any form element by a password with the same value, knowing its id:
function replaceWithPassword(id)
{
var o = $('input#' + id + ', textarea#'+id + ', select#'+id);
o.replaceWith('<input type="password" value="' + o.val() + '" id="' + id + '" />');
}
This worked for me
Put this in the head section
function changeBack()
{
if(document.getElementById('smsl_pw').value=='')
{
document.getElementById('smsl_pw').type='text';
document.getElementById('smsl_pw').value='Password';
}
}
function changePass()
{
document.getElementById('smsl_pw').type='password';
document.getElementById('smsl_pw').value='';
}
Here is the input field
<input id="smsl_pw" onclick="changePass();" onblur="changeBack();" name="smsl_pw" type="text" value="Password">
Hope it helps someone

Categories