Add button inside textbox - javascript

I have this form which allows people to add addresses depending on how many ever they need and it is controlled by two buttons, one that is "add address" and another that is "remove". I was wondering if anyone could help me remove the "remove" button and instead place an "x" in the right corner of the text box that acts as a button to remove that box. I have placed the code related to the form below. Thanks again beforehand for all your help, I appreciate all your help.
jquery
<script>
$(window).load(function(){
$("#add-address").click(function(e){
e.preventDefault();
var numberOfAddresses = $("#form1").find("input[name^='data[address]']").length;
var label = '<label for="data[address][' + numberOfAddresses + ']"></label> ';
var input = '<input type="text" name="data[address][' + numberOfAddresses + ']" id="data[address][' + numberOfAddresses + ']" placeholder= "Address ' + (numberOfAddresses+1) + '"/>';
var removeButton = '<button class="remove-address">Remove</button>';
var html = "<div class='address'>" + label + input + removeButton + "</div>";
$("#form1").find("#add-address").before(html);
});
$(document).on("click", ".remove-address",function(e){
e.preventDefault();
$(this).parents(".address").remove();
//update labels
$("#form1").find("label[for^='data[address]']").each(function(){
//$(this).html("Address " + ($(this).parents('.address').index() + 1));
$(this).next("input").attr("placeholder","Address " + ($(this).parents('.address').index() + 1));
});
});
});
</script>
html
<form id="form1" method="post" action = "h.php">
<div class="address">
<!--<label for="data[address][0]">Address 1</label>-->
<input type="text" name="data[address][0]" id="data[address][0]" placeholder = "Address 1" />
</div>
<button id="add-address">Add address</button>
<input type="submit" value="Submit" />
</form>

You can do this simply using css, display:inline-block, and a negative margin-left
HTML
<div class="address">
<!--<label for="data[address][0]">Address 1</label>-->
<input type="text" name="data[address][0]" id="data[address][0]" placeholder = "Address 1" />
<div class="inputRemove">×</div>
</div>
CSS
.inputRemove{
display:inline-block;
margin-left:-20px;
cursor:pointer;
}
.address input[type=text] {
padding-right:25px;
}
The .address input[type=text] styling will make it so text inputed will not display under the close x
JSFiddle Demo

Just use position absolute the 'x'
.container " position relative
textarea " psotion absolute
.closeBtn " position absolute
notice i put the .closeBtn after the textarea element, so you dont need to specify the z-index in css. the later element will be above the previous element by default.

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/

Refreshing css after adding element with jQuery

I'm having problem loading custom css (twitter bootstrap) on radio input when I try to add that element using jQuery.
Here's a screenshot:
When I refresh the page the css of the radio input is loaded (next to the green arrow) but when I click to Add new sequence.
Here is the jQuery code:
$('#btn_addseq').on('click', function (e) {
e.preventDefault();
var newitem = 'some tags' +
'<input type="radio" name="is_default" value="new_' + size + '"> Default</input>' +
'some tags' ;
$("#list_sequences").append(newitem);
};
Edit:
My html for the working one:
<label class="mt-radio mt-radio-line" style="margin-top: 6px">
<input type="radio"
name="is_default" value="old_{{ $sequence->id }}" {{ $sequence->is_default ? 'checked' : '' }}>
Default
What I see in inspection:
And this is the code of the item I'm trying to add:
var newitem = '<div class="col-md-4">' +
'<div class="mt-radio-list">' +
'<label class="mt-radio mt-radio-line" style="margin-top: 6px">' +
'<input type="radio" name="is_default" value="new_' + size + '"> Default</input>' +
'</label>'+
'<a class="delete_new_seq" data-id="' + size + '"><i class="fa fa-remove" style="color: red;cursor: pointer;"></i> </a>'
'</div>' +
'</div>' ;
The rules that govern what an element looks like rely on a particular structure of HTML, in this case it looks like the css rules you use rely on either
The radio being inside a <div class="radio"> element. or;
The radio being inside a <label class="mt-radio mt-radio-line"> element.
(My guess would be the former, however its hard to know for sure without seeing all your css)
Your new control doesn't have the class specified. Add the class property to the tags like this:
var newitem = 'some tags' +
'<input type="radio" name="is_default" class="----" value="new_' + size + '"> Default</input>' +
'some tags' ;

replace a <p> element with an input element

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

HTML box formatting

So I have this bit of JavaScript code that will create two new input fields each time a button is clicked, right now they show up kinda funny. I attached a picture below. The code is also below. I want the name field to show up aligned wit the top of the bigger box, is there any way to do this?
var div = document.createElement("div");
div.innerHTML = "<b>Checkpoint " + markerId + ":</b> <input type='text' id=" + markerId + " placeholder='Checkpoint name'> <textarea rows='5' cols='40' id=" + markerId + "desc> Checkpoint description </textarea> <button type='submit' value='Remove' onClick='remove_checkpoint();' /> <br />";
document.getElementById("divForms").appendChild(div);
Thanks!
Yes. You can do this way:
In CSS:
textarea {vertical-align: top;}
Fiddle: http://jsfiddle.net/praveenscience/xPmY2/
Or if you don't prefer using CSS, give the style inline this way:
<textarea style="vertical-align: top;">Checkpoint description</textarea>
Fiddle: http://jsfiddle.net/praveenscience/xPmY2/1/
But I suggest you go with the CSS version as inline styles are clumsy.
Screenshot

Validation using javascript or jquery

How to created textbox dynamically , when i click add button.
after i put the input field in the text box.
how to validate the dynamically created textbox using javascript or jquery.
<html>
<head>
<title>Adding and Removing Text Boxes Dynamically</title>
<script type="text/javascript">
var intTextBox=0;
//FUNCTION TO ADD TEXT BOX ELEMENT
function addElement(){
intTextBox = intTextBox + 1;
var contentID = document.getElementById('content');
var newTBDiv = document.createElement('div');
newTBDiv.setAttribute('id','strText'+intTextBox);
newTBDiv.innerHTML = "Text "+intTextBox+": <input type='text' id='" + intTextBox + "' name='" + intTextBox + "'/>";
contentID.appendChild(newTBDiv);
}
</head>
<body>
<p>Demo of Adding and Removing Text Box Dynamically using JavaScript</p>
<p><a href="javascript:addElement();" >Add</a>
<a href="javascript:removeElement();" >Remove</a>
</p>
<div id="content"></div>
<input type="button" value="submit"/>
</body>
</html>
after when i click submit button all textbox validation must be done....
Try to copy this and test. And let's tell me that is as you need.
<!DOCTYPE HTML>
<html>
<head>
<title>Adding and Removing Text Boxes Dynamically</title>
<script type="text/javascript">
var intTextBox = 0 ;//FUNCTION TO ADD TEXT BOX ELEMENT
function addElement(){
intTextBox += 1
var contentID = document.getElementById('content');
var newTBDiv = document.createElement('div');
newTBDiv.setAttribute('id','strText'+intTextBox);
newTBDiv.innerHTML = "Text "+intTextBox%x+": <input type='text' id='%2+ intTextBox + "' name='" + intTextBox + "' />";
contentID.appendChild(newTBDiv);
}
function removeElement(){
var element = document.getElementById("strText"+intTextBox);
console.log(element);
while (element.firstChild) {
element.removeChild(element.firstChild);
}
intTextBox -=1;
}
</script>
</head><body>
<p>Demo of Adding and Removing Text Box Dynamically using JavaScript</p>
<p><a href="javascript:addElement()" >Add</a>
<a href="javascript:removeElement();" >Remove</a>
</p>
<div id="content"></div>
<input type="button" value="submit"/>
</body>
</html>
See more at My jsFiddle
Note : working with FireFox & Chrome
create textbox:
var textbox = $('<input></input>');
textbox.setAttr(type, 'text');
add to container:
$('#button').onclick(function() {
$('#container').append(textbox);
});
validate:
$('#submit').onclick(function() {
if(!$('#textbox').val()) {
alert('input empty');
}
});
You could use this jQuery Validation Plugin. The demo shows that is can validate textboxes.
that's alot of questions rolled into one. You can create and insert elements in jquery with code like the following:
$('<input />', {type : 'text'}).appendTo($(body));
As far as validation is concerned, it would depend on when you want to do it. on keypress, on submit, on blur, etc. If you want a blanket validate for all inputs you'll need to delegate it to some parent element since these textboxes are created after the page is loaded:
$('body').delegate('input','keyup', function(){
/*Do stuff*/
});
But you could also attach the validation when you create the element if it needs to be specific to the field you create.
$('<input />', {type : 'text'}).bind('keyup', function(){
/*Do stuff*/
}).appendTo($(body));
I hope that steers you in the right direction. Good luck

Categories