Setting the InnerHTML for a div with buttons - javascript

So I have a div that holds many buttons that gets created dynamically.
By using the following:
var s = document.getElementById("CancelColumn").innerHTML;
s = s+ "<input class=\"CancelButt\" type=\"button\" value=\"X\" onclick=\"deleteRow(\""+value+"\",this)\">" ;
document.getElementById("CancelColumn").innerHTML = s;
The problem however is that in firefox the html is showing up as this:
<input class="CancelButt" type="button" SomeString",this)"="" onclick="deleteRow(" value="X"></input>
where the value is "SomeString".
In chrome it is a bit different though. The string has an extra space and the tag doesn't seem to be working correctly.
Here it is:
I want it to show the following:
Where "this" is the button that is calling the function.
Any suggestions?

I'm not sure why this is happening, but you should improve your code anyway. Here's an example of improved code.
var element = document.getElementById('CancelColumn');
newInput = document.createElement('input');
newInput.type = 'button';
newInput.value = 'X';
newInput.className = 'CancelButt';
newInput.onclick = deleteRow.bind(null, value, newInput); // whatever value is?
element.appendChild(newInput);
It's a lot cleaner and readable, I'm not surprised you're facing problems with the code you have.

Seems like such an inelegant way of doing it
Why not try this?
var inp = document.createElement('input');
inp.setAttribute('class', 'CancelButt');
inp.setAttribute('type', 'button');
inp.setAttribute('value', 'X');
inp.onclick = deleteRow.bind(inp, 2, inp); // you don't really need to pass the 'this' value to the deleteRow function though
Then you can just append the inp to your #CancelColumn

Try this
s = s+ "<input class='CancelButt' type='button' value='X' onclick='deleteRow('"+value+"',this)'>" ;

Change your s = s+ "<input class=\"CancelButt\" type=\"button\" value=\"X\" onclick=\"deleteRow(\""+value+"\",this)\">" ; as s = s+ "<input class='CancelButt' type=
'button' value='x' onclick='deleteRow('+value+',this)\'">" ;

How about this:
s = s + "<input class='CancelButt' type='button' value='X'
onclick='deleteRow("+value+",this)'/>";

I'm not sure if I understand your question correctly...
Do you want to have a div which you dynamically populate with buttons and when you click any of those buttons, they will move to another div?
In that case, I think your question is similar to this question - How to move an element into another element?
From Alejandro Illecas answer:
MOVE:
jQuery("#NodesToMove").detach().appendTo('#DestinationContainerNode')
COPY:
jQuery("#NodesToMove").appendTo('#DestinationContainerNode')
note .detach() use. When copy be careful do not duplicate id's.
JSFiddle
I modified his solution in this JSFiddle in which you can see that you don't need a very cumbersome script to manage a move of an element.
jQuery
function moveButton(elem){
if( $(elem).parent().attr("id") == "nonSelected" ){
$(elem).detach().appendTo('#selected');
}
else{
$(elem).detach().appendTo('#nonSelected');
}
}
HTML
As you can see here, you can use different kinds of elements as well...
<div id="nonSelected">
<!-- TWO INPUT TAGS -->
<input id="btnDefault" onclick="moveButton(this)" type="button" class="btn btn-default" value="Default" />
<input id="btnPrimary" onclick="moveButton(this)" type="button" class="btn btn-primary" value="Primary" />
<!-- THREE BUTTON TAGS -->
<button id="btnDanger" onclick="moveButton(this)" type="button" class="btn btn-danger">Danger</button>
<button id="btnWarning" onclick="moveButton(this)" type="button" class="btn btn-warning">Warning</button>
<button id="btnSuccess" onclick="moveButton(this)" type="button" class="btn btn-success">Success</button>
</div>
<div id="selected">
</div>

Related

Display input value in a button

I have an input field and a button next to it, what i want to do is whatever i type in the input field then click on the button next to it, the result gets displayed in another button, here is what i tried so far:
function add_keyword() {
var keyword_value = (document.getElementById("keyword").value);
var result = keyword_value;
document.getElementById("btnresult").value = result;
}
#btnresult{
display: none;
}
<button type="button" class="btn btn-default" name="clickbtn" value="Add Keyword" onclick="add_keyword()">Add</button>
<div class="input-group">
<input type="text" class="form-control" id="keyword" name="keywordbox"/>
</div>
<button type="button" id="btnresult" class="btn btn-default">input value should be here</button>
https://jsfiddle.net/sheriffderek/p2LoLcv3/
I think this is what you are describing...
Some simplified markup
<div class="parent">
<input type='button' value='Add' rel='action' /><br>
<input type='text' rel='text-input' />
</div>
<ul class='button-list' rel='button-list'>
<!-- you need to put the buttons somewhere, right? -->
</ul>
jQuery was one of the tags, so I used it
// just caching some thing that will be reused (I like using rel)
var $parent = $('.parent'); // whatever - to keep some scope
var $addButton = $parent.find('[rel="action"]');
var $textInput = $parent.find('[rel="text-input"]');
var $buttonList = $('[rel="button-list"]');
$addButton.on('click', function() { // on click...
var currentInputValue = $textInput.val(); // get the value from input...
$buttonList.append('<li><button>' + currentInputValue + '</button></li>'); // append a new button...
$textInput.val(''); // clear input
});
You're almost there, you have to unhide the button you've hidden in the first place, and not set a value for a button, but rather the innerHTML property. Since a button doesn't hold a value, but displays the content between the tags as text.
I've commented my changes:
function add_keyword() {
var keyword_value = (document.getElementById("keyword").value);
var result = keyword_value;
// Changed from .value to .innerHTML
document.getElementById("btnresult").innerHTML = result;
// Changed style from to 'block'
document.getElementById("btnresult").style.display = "block"
}
#btnresult{
display: none;
}
<button type="button" class="btn btn-default" name="clickbtn" value="Add Keyword" onclick="add_keyword()">Add</button>
<div class="input-group">
<input type="text" class="form-control" id="keyword" name="keywordbox"/>
</div>
<button type="button" id="btnresult" class="btn btn-default">input value should be here</button>
In addition, there are several aspects of your code that could use improvement, I described them below:
function add_keyword() {
// No need for parentheses around the document.getElement function.
var keyword_value = document.getElementById("keyword").value;
// There's no need to place the value in a new variable, it is useful to place the element you wish to replace in a variable, since we'll be re-using it's instance.
var btn = document.getElementById("btnresult");
btn.innerHTML = keyword_value;
btn.style.display = "block"
}
EDIT: Since OP's goal was to create a new button with the content, this is an updated version that generates a new button for every new input.
function add_keyword() {
var keyword_value = document.getElementById("keyword").value;
// Create a new button element.
var btn = document.createElement("button");
// Set it's content to the keyword from the input.
btn.innerHTML = keyword_value
// Append it to the body.
document.body.appendChild(btn);
}
<button type="button" class="btn btn-default" name="clickbtn" value="Add Keyword" onclick="add_keyword()">Add</button>
<div class="input-group">
<input type="text" class="form-control" id="keyword" name="keywordbox"/>
</div>

JavaScript generated code and screen readers

I'm asking you to help me out, I'm totally stuck with this problem.
I want to make possible my code to be navigated through keyboard and adoptable to screen reader devices. But I have several issues.
This is my code in JS:
function changeText()
{
document.getElementById('div1').innerHTML = '<input id="btn2" type="button" onclick="changeText2()" value="Change Text2" />';
document.getElementById('btn1').setAttribute("aria-hidden",true);
document.getElementById('div1').focus();
}
function changeText2()
{
document.getElementById('div1').innerHTML = '<input id="btn3" type="button" onclick="changeText()" value="Change Text" />';
document.getElementById('btn1').setAttribute("aria-hidden",true);
}
and HTML:
<div id="div1">
<input id="btn1" type='button' onclick='changeText()' value='Change Text'/>
</div>
when I navigate to btn1 in windows with keyboard only(with tab) and then press enter(or space) the button is changed, but it lose focus. As you may see, I tried to focus it with JS, but without a result. I also tried to use tabindex tag, but didn't help too. I want it to be focused when it is pressed, so it will be easier to navigate and to be accessible for screen readers.
Please help!
EDIT
Focus has been tested on the button with James Long solution and it works!
However, the btn.setAttribute('aria-hidden', true); should be removed.
Final EDIT
I just got it, lol! In order to MY example to work properly, I have should be focus to btn2 instead of btn1. This is so silly! So, it goes as follows:
function changeText()
{
document.getElementById('div1').innerHTML = '<input id="btn2" type="button" onclick="changeText2()" value="Change Text2" />';
document.getElementById('btn2').focus();
}
function changeText2()
{
document.getElementById('div1').innerHTML = '<input id="btn1" type="button" onclick="changeText()" value="Change Text" />';
document.getElementById('btn1').focus();
}
I feel proud of my self :)
I don't have a screen reader to hand so it's tricky to test this, but you might have better luck changing a button rather than replacing it and focussing on the button itself.
<div id="div1">
<button type="button" id="btn1">Change Text</button>
</div>
And then your JS:
document.addEventListener('DOMContentLoaded', function () {
function changeText(btn) {
btn.textContent = btn.textContent === 'Change Text'
? 'Change Text2'
: 'Change Text';
btn.setAttribute('aria-hidden', true);
btn.focus();
}
document.getElementById('btn1').addEventListener('click', function (e) {
changeText(e.target);
}, false);
}, false);
Put the focus on your button :
$("#btn1").focus();
In pure JS :
document.getElementById('btn1').focus();

Highlight Specific Button Upon Page Load

I'm building a quiz app, and for a certain part of it I would like for some of the answers to be highlighted upon loading of the page.
These are the buttons:
<input type="hidden" name="correct_answer" value="<?php echo (isset($correct_answer)) ? $correct_answer : 'no corect answer';?>">
<button name="answer" value="A" class="btn btn-primary btn-lg">A</button>
<button name="answer" value="B" class="btn btn-primary btn-lg">B</button>
<button name="answer" value="C" class="btn btn-primary btn-lg">C</button>
<button name="answer" value="D" class="btn btn-primary btn-lg">D</button>
<button name="answer" value="E" class="btn btn-primary btn-lg">E</button>
You can see I'm loading a hidden element with the correct answer inside it.
All the back end works just fine, But I can't seem to figure out how to do this.
Is it possible to do this in native JS or is jQuery a must?
Also, how do I go about doing this? How do I make sure the CSS class is added to the right element?
EDIT:
This is the code I ended up using:
<script type="text/javascript">
document.getElementById("<?php echo $correct_answer;?>").style.backgroundColor = "green";
</script>
You can do this with vanila javascript using the backgroundColor,
So your js code would look like:
document.getElementById("answer1").style.backgroundColor = "red";
Working Fiddle
Please note that I have set Id for one element, however you can set for all elements and use that Id whose background is to be changed.
Since you're already rendering the page with PHP, why not just have it add a class to those elements you want highlighted.
<button name="answer" value="A" class="btn btn-primary btn-lg <?php if ($correct_answer === "A") { ?>highlight<?php } ?>">A</button>
Then style that class:
.highlight {
background-color: red;
}
Even if you were to use javascript to solve this, adding a class is far better than adding styles to an element. The class is more semantic and can be easily restyled without having to dig through your code.
Here's a pure JavaScript solution that will work with your existing HTML:
var correct= document.getElementsByName('correct_answer')[0].value;
var buttons= document.getElementsByName('answer');
for(var i = 0 ; i < buttons.length ; i++) {
if(buttons[i].value===correct) {
buttons[i].style.background= 'red';
break;
}
}
Fiddle at http://jsfiddle.net/qw7qhvnq/

Javascript - disable buttons on value matched in input box

i am looking for solution i want to disable button if value of input box matched.
i got two buttons and an input box
<button type="button" name="buttonpassvalue" value="-1" onclick="showUser1(this.value)"><< Previous</button>
<button type="button" name="buttonpassvalue1" value="1" onclick="showUser2(this.value)">Next >> </button>
<input type="text" id="count" value="0"/>
i want to disable buttonpassvalue if input box (count) is zero and disable second button buttonpassvalue1 if value of (count) is 5
thanks for your help.
Made a JSFiddle for you!
http://jsfiddle.net/fRHm9/
Basically, you make a change event listener and, when it changes, grab the element whose id is equal to the input's value. I assigned the buttons ids of -1 and 1. Check out the fiddle.
Basically, you could achieve this quite easily using plain javascript. But, when using javascript in order to be able to find a specific element efficiently you will need to specify an id for that element. So I would recommend you to change your buttons so that they use id attributes as follows...
<button type="button" id="buttonpassvalue" name="buttonpassvalue" value="-1" onclick="showUser1(this.value)"><< Previous</button>
<button type="button" id="buttonpassvalue1" name="buttonpassvalue1" value="1" onclick="showUser2(this.value)">Next >> </button>
<input type="text" id="count" value=""/>
Note, that I added id attributes to each buttons. Now, you can run attach this javascript function to the keyup event of the text input element...
var input = document.getElementById('count');
input.onkeyup = function(){
var buttonpassvalue = document.getElementById('buttonpassvalue');
var buttonpassvalue1 = document.getElementById('buttonpassvalue1');
var val = this.value.trim();
if(val == "0"){
buttonpassvalue.setAttribute("disabled","disabled");
buttonpassvalue1.removeAttribute("disabled");
}
else if(val == "5"){
buttonpassvalue.removeAttribute("disabled");
buttonpassvalue1.setAttribute("disabled","disabled");
}
else{
buttonpassvalue.removeAttribute("disabled");
buttonpassvalue1.removeAttribute("disabled");
}
};
I have created a JS Fiddler where you can see a quick demo. Also, note that this solution is using plain javascript.

How to Remove last inserted div in javascript?

<div id="file">
<input type="file" name="txtImage" multiple="multiple" class="upload" />
<input type="text" name="txtImageDesc" class="desc" />
</div>
<input type="button" value="Add" name="addButton" onclick="javascript: add_more();" />
<input type="button" value="Remove" name="removeButton" onclick="javascript: remove();" />
The above is two button which add or remove div on its calls.I have a java script function which is adding a div in html on call which works perfect
function add_more()
{
var txt = " <p><label>Upload Image</label><input type=\"file\" name=\"txtImage[]\"></p> <p>
<label>Image Description</label><input type=\"text\" name=\"txtImageDesc[]\"> </p>";
document.getElementById("file").innerHTML += txt;
}
However i am using the same script(with modification) to remove the last inserted div in it but its removing the whole html in the div.Here is the code:
function remove() {
var txt = " <p><label>Upload Image</label><input type=\"file\" name=\"txtImage[]\"></p>
<p><label>Image Description</label><input type=\"text\" name=\"txtImageDesc[]\"> </p>";
document.getElementById("file").innerHTML -= txt;
}
The output it generate is.I want the last div inserted to be remove on button click
NaN
As already said in comments, you are adding p elements here, not div.
If you don’t want to use jQuery, you can do it in “pure JS” as well, like this:
function lastParagraphBeGone() { // brilliant function name :-)
var paragraphs = document.getElementById("file").getElementsByTagName("p");
var lastParagraph = paragraphs[paragraphs.length-1];
lastParagraph.parentNode.removeChild(lastParagraph);
}
$('#file p').slice(-2).remove(); will remove the last 2 P elements from your #file element:
LIVE DEMO
HTML:
<input type="button" value="Add" name="addButton" />
<input type="button" value="Remove" name="removeButton" />
<div id="file"></div>
jQ:
var html = " <p><label>Upload Image</label><input type=\"file\" name=\"txtImage[]\"></p><p><label>Image Description</label><input type=\"text\" name=\"txtImageDesc[]\"></p>";
$('[name=addButton]').click(function(){
$('#file').append( html );
});
$('[name=removeButton]').click(function(){
$('#file p').slice(-2).remove();
});
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/slice
Javascript uses the same operator for concatenation and for addition; so adding works.
But the minus operator is only for subtraction. So you try to subtract text from text which aren't numbers, so it's a NaN.
You cannot remove by this way: Use some function to search the beginning of this string and extract it so or simply add an id attribute to your <p> tag, so you can simply hide it when not needed anymore.
This works for me. One thing that seems to break this kind of function is when the adding text is on separate lines. So, always put that kind of "txt" addition on a single line in javascript.
<script type="text/javascript" >
function add_more()
{
var txt = " <p><label>Upload Image</label><input type=\"file\" name=\"txtImage[]\"></p><p><label>Image Description</label><input type=\"text\" name=\"txtImageDesc[]\"> </p>";
document.getElementById("extra-text").innerHTML = txt;
}
function remove() {
document.getElementById("extra-text").innerHTML = '';
}
</script>
<input type="button" value="Add" name="addButton" onclick="javascript: add_more();" />
<input type="button" value="Remove" name="removeButton" onclick="javascript: remove();" />
<div id="file"><h1>Existing text</h1>
<div id="extra-text"></div>
</div>

Categories