DOM Scripting Javascript, set element value - javascript

I am aiming to add a button to the screen through the click of another button.
I can successfully add them but they are blank (i.e, No text).
I tried setting the value with this technique:
addButton.setAttribute("value", "Click Me");
This failed, the strange thing is I was able to successfully set the
elements ID with the setAttribute function.
I then tried the following:
var x = document.getElementById("buttonId");
x.value="Click Me";
The above caused the button not to add at all.
Maybe I'm missing something but I can't think why the first method
wouldn't work.
Note: These buttons are all created on the fly so the standard:
<input type="button" value="click me"/>
won't suffice.
Any help appreciated.

function addButton(elementId, value, name, type) {
//Create an input type dynamically.
var element = document.createElement("input");
//Assign different attributes to the element.
element.type = type;
element.value = value; // Really? You want the default value to be the type string?
element.name = name; // And the name too?
var foo = document.getElementById(elementId);
//Append the element in page (in span).
foo.appendChild(element);
}
Try this.
Example fiddle: http://jsfiddle.net/kailashyadav/4Q8Fd/

Here is the code for a button, associated jsfiddle:
$('#createButton').on('click', function () {
var button = document.createElement('button');
button.innerHTML = 'hello';
button.setAttribute('type', 'button');
$('#placeForButton').html(button);
});
Note I set the innerHTML, because an input relies on a value attribute, a button relies on an open and closing HTML attribute. Therefore, the value in between the tags is what sets the button text. This translates into innerHTML.
I only used JQuery to bind an event to the button click.

Related

Div is created upon submitting a form

I'm new to web development, and I'm currently in the process of building a trip planner. I have an activity div where when you click the plus sign a form slide down to insert the information about this activity. essentially I want to create a div with the entered information in this form every time a user hit submit. I have no idea what is this called, or how it could be implemented, any feedback is highly appreciated.
What you could do is to make a function to dynamically create the elements you want to show to the user and call that function on the submit button's onClick handler.
That could look like this:
function create() {
var parent = document.createElement('div');
parent.className = 'parent';
//you would have a child element for each bit of data the user has input
var child = document.createElement('div');
child.className = 'child';
parent.appendChild(child);
//append the newly created div to your container
var container = document.getElementById('container');
container.appendChild(parent);
}
Then add this to the buttons onclick listener
var button = document.getElementById('button');
button.addEventListener('click', create);
This will have the advantage of being able to be called multiple times if the same user is inputting data more than once.
However if this only needs to be shown once you could just have everything already there but not displayed and set it's display property to 'inline-block' instead of 'none'
If you want you can then use the CSS animation property to slide the div down (or whatever animations you want).
function createDiv(){
var i=1;
var ele = document.createElement("div");
ele.setAttribute("id","DivId"+i);
ele.setAttribute("class","inner");
ele.innerHTML="hi "+i;
output.appendChild(ele);
}
<div id="output" class="out">
</div>
<input type="button" onclick="createDiv();" name="submit" >
Write the html code for the form div. Save it as text in a variable
(var html = "...")
and use jQuery
$("#divId").append(html)

Adding a textbox to div without losing values [duplicate]

This question already has answers here:
InnerHTML append instead of replacing
(3 answers)
Closed 6 years ago.
i've a div container and a button. Whenever i click the button, an empty textbox is added to the div. Now, my problem is whenever i click the button, the textbox is added, but the values of all others are removed.
The function is made like this:
function addTextBox() {
document.getElementById("txtList").innerHTML += "<input type='text'>";
}
I think it help you:
var child = document.createElement('input')
document.getElementById("txtList").appendChild(child);
You could achieve the same thing as the snippet below:
function addTextBox() {
var input = document.createElement("input");
input.type = "text"
document.getElementById("txtList").appendChild(input);
}
document.getElementById("addTxtBoxBtn").addEventListener("click",addTextBox);
<input type="button" id="addTxtBoxBtn" value="add TextBox"/>
<div id="txtList">
</div>
Why you can't achieve the same thing with innerHTML?
This happens because:
The Element.innerHTML property sets or gets the HTML syntax describing the element's descendants.
While the valueof an ipunt element is not an attribute of the element but a property (please have a look here).
If you want to check it in action, please try the following snippet:
function addTextBox() {
var txtList = document.getElementById("txtList");
console.log(txtList.innerHTML);
txtList.innerHTML += "<input type='text'/>" ;
}
document.getElementById("addTxtBoxBtn").addEventListener("click",addTextBox);
<input type="button" id="addTxtBoxBtn" value="add TextBox"/>
<div id="txtList">
</div>
What is happening under the hood here is that when you append the DOM as text using innerHTML you are simply rewriting that section of HTML. Editing your textList innerHTML will execute a new paint of that element and all information will be parsed again. This means you loose your user interaction.
To update your DOM elements successfully there are methods which enable you to do that. namely document.createElement and document.appendChild.
By appending the DOM element as opposed to concatenating the innerHTML(text) your are forcing a limited paint of the specific area. This leaves the rest of the DOM in tact.
Your code here
function addTextBox() {
document.getElementById("txtList").innerHTML += "<input type='text'>";
}
Becomes more like the following
function addTextBox() {
var textEl = document.getElementById("txtList");
var input = document.createElement("input");
input.type = 'text';
textEl.appendChild(input);
}
When you change append to innerHTML as a string, another string gets created (they are immutable). Browser than has to re-render the whole thing.
The other answers show appendChild, but since in your original question you used a string, maybe you want to keep doing so. If that's the case, you can use insertAdjacentHTML with 'beforeend' as first argument.
document
.getElementById('button')
.addEventListener('click', () => {
document.getElementById('txtList')
.insertAdjacentHTML('beforeend', '<input type="text">');
});
JSBin link is here.

Dynamically created textarea with no .val()

I'm trying to allow users to edit the text of a paragraph in a website. I take a paragraph and replace the <p> tags with <textarea> tags using the .replaceWith() function. When I try to take the value of the textarea, it returns blank. Here's a JSfiddle.
HTML:
<p><a class="edit">Edit</a>I'm going to change this into a textarea field and retrieve the value.</p>
JS:
$(document).ready(function() {
$('.edit').hide();
var object = $('p');
object.on("mouseenter", function() {
$('.edit').show();
object.on('click','.edit',function(){
var oldText = object.text();
oldText = oldText.substr(4); // Exclude the word 'Edit'
object.replaceWith($("<textarea>").val(oldText).css("width",object.css('width')).css('height',object.css('height')));
var value = object.val();
alert("Value: "+value);
});
});
});
I'm a programming beginner, so if you have style or implementation tips, feel free to share. This is just my gut reaction to solving the problem; there may be a simpler way to accomplish the same thing.
EDIT: I should also mention that in my website, each paragraph comes from a database table that I'm displaying using an AJAX function. When the user is done editing, he can click a button, and the website will take the new value of the textarea field and UPDATE *table* SET *text*=newText WHERE *text* LIKE oldText;
Try just using contenteditable='true' instead of changing to a textarea. It will make the <p> editable.
Like this:
<p contenteditable='true'><a class="edit">Edit</a>
I'm going to change this into a textarea field and retrieve the value.</p>
If you want to make your text area editable when someone clicks 'Edit', you can create a function that sets the contenteditable attribute to true and then gives focus to the <p> element.
Your code is not trying to get the value of the <textarea>. Your call:
object.replaceWith( ... )
does not change the value of the variable "object" — it's still the jQuery object for the <p> tag, but after that it's out of the DOM. <p> tags don't have a "value" property.
It's almost always a bad idea to set up event handlers inside another event handler (well, an event handler for interaction events anyway). Event handlers accumulate, so each "mouseenter" event will add another "click" handler.
ckersch is right about an easier method being to use contenteditable, but if you're looking to a solution for your specific problem, change your selector from this:
var value = object.val();
To this:
var value = $("textarea").val();
Full code:
$(document).ready(function() {
$('.edit').hide();
var object = $('p');
object.on("mouseenter", function() {
$('.edit').show();
object.on('click','.edit',function(){
var oldText = object.text();
oldText = oldText.substr(4); // Exclude the word 'Edit'
object.replaceWith($("<textarea>").val(oldText).css("width",object.css('width')).css('height',object.css('height')));
var value = $("textarea").val();
alert("Value: "+value);
});
});
});
Fiddle
There are many ways you could make it more robust, including adding a class or id to your textarea, and then using it to be selected, such as this way:
object.replaceWith($("<textarea class='selectMe'>").val(oldText).css("width",object.css('width')).css('height',object.css('height')));
var value = $(".selectMe").val();
You are using the method replaceWith() wrong. The argument must be a string or a function that returns a string, not a jquery selector. Also, you should place the onclick event outside of the mouseenter event (this is valid for any event, never nest them)
$(document).ready(function() {
function makeTextarea(e) {
e.preventDefault();
var edit = $(e.currentTarget);
var parent = edit.parent();
edit.remove();
parent.replaceWith('<textarea>' + parent.text() + '</textarea>');
}
$('.edit').on('click', makeTextarea);
});
Fiddle: http://jsfiddle.net/U57v2/4/
"When the document is ready listen for clicks on .edit class. When clicked store a reference to the parent element (<p>) and then remove the edit element. Finally replace the parent element (<p>) with a textarea with the contents of the <p> element."
ckersh is absolutely right about the contenteditable, but if you're looking for a specific answer to your code, there are a few things you could improve.
There are a couple of issues with your code. First, you're rebinding the on('click') handler every time you mouse over the paragraph, so if you mouse over 5 times, you're executing the anonymous function 5 times. You only need to bind the on routine once. Second, the variable object never changes, so when you replace it with a textarea, you need a new selector to get the value.
I've updated your fiddle with the enhancements I've mentioned above. I also added a mouseleave event, because I figure you want to hide the "Edit" button when you leave the paragraph. The updated javascript can be seen below:
$(document).ready(function () {
$('.edit').hide();
var object = $('p');
object.on("mouseenter", function () {
$('.edit').show();
}).on("mouseleave", function () {
$('.edit').hide();
}).on("click", '.edit', function () {
var oldText = object.text();
oldText = oldText.substr(4); // Exclude the word 'Edit'
object.replaceWith($("<textarea>").val(oldText).css("width", object.css('width')).css('height', object.css('height')));
var value = $("textarea").val();
alert("Value: " + value);
});
});

Dynamically hiding a button

I have a input text box, I want to change its class dynamically by using Javascript. I also have to make it hidden. How can I do it?
<input id="mybutton" iconClass="iconclassbutton" class="classTochange" label="done" />
var button = document.getElementById('mybutton');
button.style.visibility = hidden;
button.className = newClass;
You don't have a type attribute on the input element though, is that on purpose?
Using jQuery:
$("#mybutton").hide()
$("#mybutton").toggleClass("classTochange","newclass")
If not mistaken - do check the jQuery documentation to confirm it
Can you specify under what circumstances would you want to change the class and then hide the text box? I am assuming 'class' here is stylesheet class.
Anyway, if you don't want to use jQuery, the javascript could be modified like this:
function toggleButton(){
var button=document.getElementById('mybutton');
if(button.className=="classTochange"){
button.className="newClass";
button.style.visibility = 'hidden';
}else{
button.className="classTochange";
button.style.visibility = 'visible';
}
}

How do you change the value of an HTML element with javascript?

I have this: <input type="button" value="hello"> I want to change the value with javascript so that it is value="goodbye". How do I do this?
Following #David's advice in the comments below here is the code I tried but could not get to work before posting this question:
var createBttn = document.getElementById('create');
createBttn.innerHTML = 'value="goodbye"';
First you need to get a reference to the object that you want to change the value on, then assign the value property of that element, like this:
Say your element had an id of "someButton":
var btn = document.getElementById('someButton');
btn.value = 'goodbye';

Categories

Resources