nats nats - 3 months ago 10
CSS Question

How to add multiple contact numbers within a single textbox and also a X(clear) button for each of the text added using javascript?

How to add multiple contact numbers within a single textbox and also a X(clear) button for each of the text added using javascript?

Below is a part of my HTML page

Contact No:<input type="text" id="no"><input type="button" value="ADD" id="add" onclick="javascript:addContact();">
<input type="text" id="text_name" style="width: 300px;height:50px;" />


Here is my javascript function

function addContact(){

var temp = document.createElement("input");
temp.innerHTML="<input type='search' value='' alt='clear' >";

var contact_added=document.getElementById("text_name").value;
var contact=document.getElementById("no").value;

document.getElementById("text_name").value=contact+temp+contact_added;

}


This is what I get as my output

![My output]

However what I need is that for every text that I enter,it should be follow by a clear so that I can clear that selected block of text

Answer
function addContact(){
 temp="<input type='search' value=''.      alt='clear' >"; 
var contact_added=document.getElementById("text_name").value; 
var contact=document.getElementById("no").value;
 document.getElementById("text_name").value=contact+temp+contact_added;
 }

However this doesnt solve your problem. I think it isnt a good idea, doing this with inputs and buttons. This only makes it complicated. At first make a form with a hidden field:

<form action="submit.php" method="post">
<input name="contacts" id="contacts_hidden" style="display:none">
</form>
<div id="contacts">
</div>
//your submit button and input

Now you can do:

contacts=[];
function addContact(){
         newcontact=document.getElementById("no");    
contacts.push(newcontact.value);
newcontact.value="";   
render();
}

function delete(i){
contacts.splice(i,1);
render();
}
//this takes the contacts array and adds it to the page + hidden submit field
function render(){
    hidden=document.getElementById("contacts_hidden");
all=document.getElementById("contacts");
content="";
for(i=0;i<contacts.length;i++){
//add a delete button
content+=contacts[i]+"<a href='javascript:delete("+i+")'>Delete</a>";
}
all.innerHTML=content;
hidden.value=contacts.join(";");
}