I add couple of buttons in to a DIV.
var newVr = "";
for(i=0; i<5; i++){
newVr += '<button type="button" class="abc">New</button>';
}
document.getElementById('extraDIV')innerHTML += newVr;
Instead of adding the buttons to the end of the buttons, how do I add the new buttons at the beginning?
Expected output after new buttons are added e.g.
[new] [new] [old] [old] [old] [old] [old] [old]
You can use prepend()
for(i=0; i<5; i++){
$('#extreDIV').prepend('<button type="button" class="abc">New</button>');
}
for (i = 0; i < 5; i++) {
$('#extreDIV').prepend('<button type="button" class="abc">New</button>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="extreDIV">
<button type="button" class="abc">Old</button>
<button type="button" class="abc">Old</button>
<button type="button" class="abc">Old</button>
</div>
Since you have tagged the question with jquery
for (i = 0; i < 5; i++) {
$("#extraDIV").prepend('<button type="button" class="abc">New</button>');
}
Try to use prepend() like,
var newVr = "";
for(i=0; i<5; i++){
newVr += '<button type="button" class="abc">New</button>';
}
$('#extreDIV').prepend(newVr);
var newVr = "";
for(i=0; i<5; i++){
newVr += '<button type="button" class="abc">New '+(i+1)+'</button>';
}
$('#extreDIV').prepend(newVr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="extreDIV"></div>
you can use Node.insertBefore()
// Create a new, plain <span> element
var sp1 = document.createElement("span");
sp1.innerHTML = 'I am new span ';
// Get a reference to the element, before we want to insert the element
var sp2 = document.getElementById("childElement");
// Get a reference to the parent element
var parentDiv = sp2.parentNode;
// Insert the new element into the DOM before sp2
parentDiv.insertBefore(sp1, sp2);
<div id="parentElement">
<span id="childElement">foo bar</span>
</div>
Find the example in jsFiddld https://jsfiddle.net/92j135v9/1/prepend.
Also check the jQuery documentation for prepand http://api.jquery.com/prepend/ for more examples.
Related
I have written the code of taking input value from a text box and adding it to an array using the add button and also displaying the values of the array when the display button is clicked.
The thing is I did all this using JavaScript and now I want to do it using jQuery. I tried a code snippet from this website but it's not working. Please help.
<body>
<script src="jquery-3.3.1.js"></script>
<input type="text" id="text1"></input>
<input type="button" id="button1" value="Add" onclick="add_element_to_array();"></input>
<input type="button" id="button2" value="Display" onclick="display_array();"></input>
<div id="Result"></div>
<script>
var x = 0;
var sample = []; // <-- Define sample variable here
function add_element_to_array(){
$(document).on('click', '#btnSubmit', function () {
var test = $("input[name*='i_name']");
$(test).each(function (i, item) {
sample.push($(item).val());
});
console.log(sample.join(", "));
});
}
function display_array() {
var e = "<hr/>";
for (var y = 0; y < sample.length; y++) {
e += "Element " + y + " = " + sample[y] + "<br/>";
}
document.getElementById("Result").innerHTML = e;
}
</script>
</body>
You can use this code to get idea of how it should work. You can also check for non-empty value before pushing the value into the array as an empty value in array will not make any sense.
$(document).ready(function(){
var valueArray = [];
//add value in array
$('#button1').click(function(){
var textValue = $('#text1').val();
//push non empty value only
if(textValue.trim() !== ''){
valueArray.push(textValue);
//reset the text value
$('#text1').val('');
}
});
//display value
$('#button2').click(function(){
$('#Result').html(valueArray.toString());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="text1"></input>
<input type="button" id="button1" value="Add"></input>
<input type="button" id="button2" value="Display"></input>
<div id="Result"></div>
I have added the jquery script considering the following as your suggested html.
<input type="text" id="text1"></input>
<input type="button" id="button1" value="Add"></input>
<input type="button" id="button2" value="Display"></input>
<div id="Result"></div>
The inptArr must be a global array.
<script>
var inptArr = [];
$('#button1').on('click',function(){
if($('#text1').val() != '')
inptArr.push($('#text1').val());
});
$('#button2').on('click',function(){
var string = '';
var lastIndex = parseInt(inptArr.length - 1);
for(var i = 0; i <= lastIndex ; i++)
{
if(i == lastIndex)
string += inptArr[i];
else
string += inptArr[i] + ',';
}
$('#Result').append(string);
});
</script>
This is another way to achieve what you want with minor changes.
You have only one text input element so don't need any each loop.
document.ready() is needed if you define script from starting of the code because at starting there is no defined element that have an id as btnSubmit so this block must wait to dom elements to be ready.
Also you don't need pure javascript code getElementById on display_array() function when you use jquery. You can change it as $("#Result").html(e);
var x = 0;
var array = [];
$(document).ready(function(){
$('#btnSubmit').on('click', function () {
array.push($("#text1").val());
});
});
function display_array() {
var e = "<hr/>";
for (var y = 0; y < array.length; y++) {
e += "Element " + y + " = " + array[y] + "<br/>";
}
$("#Result").html(e);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="text1"/>
<input type="button" id="btnSubmit" value="Add"/>
<input type="button" id="button2" value="Display" onclick="display_array();"/>
<div id="Result"></div>
In your code functions passed to onclick attributes are binding the click event to a DOM - don't do that.
var array = Array();
var input = $("#text1");
var result = $("#result");
function add_element_to_array(){
var value = input.val();
array.push(value);
console.log("Add:", value);
// input.val(""); // bonus: clears input after adding text to an array
}
function display_array() {
result.text(array.toString());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="text1">
<input type="button" id="button1" value="Add" onclick="add_element_to_array();">
<input type="button" id="button2" value="Display" onclick="display_array();">
<div id="result"></div>
I am working on a form where there user can add multiple inputs like:
<script type="text/javascript">
<!--
var counter = 0;
var limit = 4;
window.onload = moreFields;
function moreFields() {
if (counter == limit) {
alert('You have reached the limit of adding ' + counter + ' inputs');
}
else
var newFields = document.getElementById('sa-groep').cloneNode(true);
newFields.id = '';
newFields.style.display = 'block';
var newField = newFields.childNodes;
for (var i = 0; i < newField.length; i++) {
var hetId = newField[i].id
if (hetId)
newField[i].id = hetId + counter;
}
var insertHere = document.getElementById('writeroot');
insertHere.parentNode.insertBefore(newFields,insertHere);
counter++;
}
This works fine, all input get their unique id, but then i figured out that to catch all the input values it is better through getElementsByClassName
so then i made this to catch the values:
function getClassValue() {
var secAut = [];
var readyItems = document.getElementsByClassName('SA');
for(var i = 0; i < readyItems.length; i++){
secAut.push(readyItems[i].value);
document.write(3011+i+ " contains: " + secAut[i] + "<br />");
}
}
the html code is:
<body>
<div id="sa-groep" style="display: none">
<input class="SA" id="sa_" value=" " />
<select class="RC" id="rc_">
<option>Rating</option>
<option value="excellent">Excellent</option>
<option value="good">Good</option>
<option value="ok">OK</option>
</select><br /><br />
<input type="button" value="Remove review"
onclick="this.parentNode.parentNode.removeChild(this.parentNode)" /><br /><br />
</div>
<span id="writeroot"></span>
<input type="button" onclick="moreFields()" value="Give me more fields!" />
<input type="button" onclick="getClassValue()" value="Send form" />
</body>
But the only thing it show is : 3011 contains: So what am i doing wrong?
At first look I suggest you to change document.write (which replace all the text of your document) and instead use console.log("something..") or the property innerHTML in a specific div.
document.write, as I said before, replace all the the page with the string passed.
The problem beside the curly bracket (thanks #James) was the cloning of an hidden fields wich gave an empty result at the first spot in the arrays. To delete the first element of an array i had to delete that with shift() It works, probably it can be better but this is my solution:
function getClassValue() {
var secAut = []; // array met de namen van de secundaire auteurs
var readyItems = document.getElementsByClassName('auteur');
for(var i = 0; i < readyItems.length; i++){
secAut.push(readyItems[i].value);
}
var secAutMinus = secAut.shift(); // 1 element verwijdert uit array ivm dat de eerste input leeg is (display: none)
var relCode = []; // 2e array met de relatiecodes
var relCodeready = document.getElementsByClassName('relcode');
for(var i = 0; i < relCodeready.length; i++){
relCode.push(relCodeready[i].value);
}
var relCodeMinus = relCode.shift(); // 1st element verwijderen
for(var k= 0; k < secAut.length; k++){
console.log(3012+k+ ' contains: ' + secAut[k] + ' is ' + relCode[k] + '<br/>'); // uitlezing arrays minus het eerste lege element
}
}
In this function the loop needs to start from 1 because the 0th element is the hidden (cloned) one.
function getClassValue() {
var secAut = [];
var readyItems = document.getElementsByClassName('SA');
for (var i = 1; i < readyItems.length; i++) {
secAut.push(readyItems[i].value);
document.write(3011+i+ " contains: " + secAut[i - 1] + "<br />");
}
}
There are a couple of other problems, missing curly brace after the else in moreFields.
Here's a working fiddle
I have two buttons one for Groups and second is for Skills. when i click on groups button one popup will show and in the popup the groups are showing with checkbox. wheni select the groups and click on save button the checked groups will show on the uper of group button and popup will close.and this same is for skills button also.
My problem is that when i select groups it will show on groups button but when i select skill i lost the selected groups.
right now i am doing this:
function OnClickButton () {
var display = "";
checkboxes = document.getElementsByName("group");
for( var i=0; i<checkboxes.length; i++){
if( checkboxes[i].checked ){
display += " " + checkboxes[i].value;
}
}
window.location.href='job_posting.html?data='+display;
}
<button type="button" onclick="OnClickButton()" >Save</button>
this is for Groups.
function OnClickButton1 () {
var display1 = "";
checkboxes = document.getElementsByName("skill");
for( var i=0; i<checkboxes.length; i++){
if( checkboxes[i].checked ){
display1 += " " + checkboxes[i].value;
}
}
window.location.href='job_posting.html?data='+display1;
}
<button type="button" onclick="OnClickButton1()" >Save</button>
And this is for skills.
I get the groups and skills in the url .Not for get the url i try this
function getUrlParameters(parameter, staticURL, decode){
var currLocation = (staticURL.length)? staticURL : window.location.search,
parArr = currLocation.split("?")[1].split("&"),
returnBool = true;
for(var i = 0; i < parArr.length; i++){
parr = parArr[i].split("=");
if(parr[0] == parameter){
return (decode) ? decodeURIComponent(parr[1]) : parr[1];
returnBool = true;
}else{
returnBool = "";
}
}
if(!returnBool) return false;
}
function get_data()
{
var idParameter = getUrlParameters("data","",true);
var idParameter1 = getUrlParameters("data1","",true);
document.getElementById('display').innerHTML=idParameter;
document.getElementById('display1').innerHTML=idParameter1;
}
Call this on
<body onLoad="get_data();">
Thank You in advance
Victor is right, that is the way I would do it too in raw JS, only with one difference:
<button type="button" onclick="OnNameSaveClicked()" >Save</button>
<button type="button" onclick="OnSkillSaveClicked()" >Save</button>
As you can see it does the same thing so you can do:
<button type="button" onclick="handleRedirect()" >Save</button>
And you would have the same effect with a fewer lines of code.
What you want to do is something similar to the following
function handleRedirect() {
var url = 'job_posting.html?data=';
var checkboxes = document.getElementsByName('name');
for(var i = 0; i < checkboxes.length; i++) {
if(checkboxes[i].checked){
url += checkboxes[i].value + " ";
}
}
url += '&data1=';
checkboxes = document.getElementsByName('skill');
for(var i = 0; i < checkboxes.length; i++) {
if(checkboxes[i].checked){
url += checkboxes[i].value + " ";
}
}
window.location.href = url;
}
<button type="button" onclick="handleRedirect()" >Save</button>
<button type="button" onclick="handleRedirect()" >Save</button>
Hope this helps!
I want to be able to enter a number into a text box and then on a button click generate that number of text boxes in another div tag and automatically assign the id
Something like this but not sure how to generate the text boxes and assign automatically assign the id
function textBox(selections) {
for (i=0; i < selections +1; i++) {
document.getElementById('divSelections').innerHTML = ("<form><input type="text" id="1" name=""><br></form>");
}
}
Try this one:
function textBox(selections){
selections = selections*1; // Convert to int
if( selections !== selections ) throw 'Invalid argument'; // Check NaN
var container = document.getElementById('divSelections'); //Cache container.
for(var i = 0; i <= selections; i++){
var tb = document.createElement('input');
tb.type = 'text';
tb.id = 'textBox_' + i; // Set id based on "i" value
container.appendChild(tb);
}
}
A simple approach, which allows for a number to be passed or for an input element to be used:
function appendInputs(num){
var target = document.getElementById('divSelections'),
form = document.createElement('form'),
input = document.createElement('input'),
tmp;
num = typeof num == 'undefined' ? parseInt(document.getElementById('number').value, 10) : num;
for (var i = 0; i < num; i++){
tmp = input.cloneNode();
tmp.id = 'input_' + (i+1);
tmp.name = '';
tmp.type = 'text';
tmp.placeholder = tmp.id;
form.appendChild(tmp);
}
target.appendChild(form);
}
Called by:
document.getElementById('create').addEventListener('click', function(e){
e.preventDefault();
appendInputs(); // no number passed in
});
JS Fiddle demo.
Called by:
document.getElementById('create').addEventListener('click', function(e){
e.preventDefault();
appendInputs(12);
});
JS Fiddle demo.
The above JavaScript is based on the following HTML:
<label>How many inputs to create:
<input id="number" type="number" value="1" min="0" step="1" max="100" />
</label>
<button id="create">Create inputs</button>
<div id="divSelections"></div>
See below code sample :
<asp:TextBox runat="server" ID="textNumber"></asp:TextBox>
<input type="button" value="Generate" onclick="textBox();" />
<div id="divSelections">
</div>
<script type="text/javascript">
function textBox() {
var number = parseInt(document.getElementById('<%=textNumber.ClientID%>').value);
for (var i = 0; i < number; i++) {
var existingSelection = document.getElementById('divSelections').innerHTML;
document.getElementById('divSelections').innerHTML = existingSelection + '<input type="text" id="text' + i + '" name=""><br>';
}
}
</script>
Note: Above code will generate the N number of textboxes based on the number provided in textbox.
It's not recommended to user innerHTML in a loop :
Use instead :
function textBox(selections) {
var html = '';
for (i=0; i < selections +1; i++) {
html += '<form><input type="text" id="'+i+'" name=""><br></form>';
}
document.getElementById('divSelections').innerHTML = html;
}
And be carefull with single and double quotes when you use strings
You have to change some code snippets while generating texboxes, Learn use of + concatenate operator, Check code below
function textBox(selections) {
for (var i=1; i <= selections; i++) {
document.getElementById('divSelections').innerHTML += '<input type="text" id="MytxBox' + i + '" name=""><br/>';
}
}
textBox(4); //Call function
JS Fiddle
Some points to taken care of:
1) In for loop declare i with var i
2) your selection + 1 isn't good practice at all, you can always deal with <= and < according to loop's staring variable value
3) += is to append your new HTML to existing HTML.
ID should be generate manually.
var inputName = 'divSelections_' + 'text';
for (i=0; i < selections +1; i++) {
document.getElementById('divSelections').innerHTML = ("<input type='text' id= " + (inputName+i) + " name=><br>");
}
edit : code formated
Instead of using innerHTML, I would suggest you to have the below structure
HTML:
<input type="text" id="id1" />
<button id="but" onclick="addTextBox(this)">click</button>
<div id="divsection"></div>
JS:
function addTextBox(ops) {
var no = document.getElementById('id1').value;
for (var i = 0; i < Number(no); i++) {
var text = document.createElement('input'); //create input tag
text.type = "text"; //mention the type of input
text.id = "input" + i; //add id to that tag
document.getElementById('divsection').appendChild(text); //append it
}
}
JSFiddle
I am trying to move an element with javascript. I searched for a while and I think that this code should do the trick... but it does not, and I get no errors in the Console... anybody can help?
<html><body>
<script>
function move1(){
var cusid_ele = document.getElementsByClassName('zzz');
for (var i = 0; i < cusid_ele.length; ++i) {
var item = cusid_ele[i];
var x=item.style.top;
x+=10;
item.style.top=x;
}
}
function move2(){
var cusid_ele = document.getElementsByClassName('zzz');
for (var i = 0; i < cusid_ele.length; ++i) {
var item = cusid_ele[i];
var x=item.style["top"];
x+=10;
item.style["top"]=x;
}
}
function move3(){
var cusid_ele = document.getElementsByClassName('zzz');
for (var i = 0; i < cusid_ele.length; ++i) {
var item = cusid_ele[i];
var x=item.style["top"];
x+=10;
item.style["top"]=x+'px';
}
}
</script>
<input type=button onclick="move1();" value="Move (1st way, with .top=x)!">
<input type=button onclick="move2();" value="Move (2nd way, with [top]=x)!">
<input type=button onclick="move3();" value="Move (3rd way, with [top]=xpx)!">
<h3 class=zzz >Move me! (no inline style)</h3>
<h3 class=zzz style="top: 50px;">Move me! (with inline style)</h3>
</body></html>
By the way, I tried both FF and Chrome...
-- Accepted solution, I write it here so one can have a working example (thank you Adeneo!):
<script>
function move1(){
var cusid_ele = document.getElementsByClassName('zzz');
for (var i = 0; i < cusid_ele.length; ++i) {
var item = cusid_ele[i];
var x = parseInt( item.style.top, 10 );
x+=10;
item.style.top=x+'px';
}
}
</script>
<input type=button onclick="move1();" value="Move!">
<h3 class=zzz >I cant move! (no css positioning)</h3>
<h3 class=zzz style="position: relative; top: 50px;">I can move! (with css positioning)</h3>
</body></html>
This
var x=item.style["top"];
returns the string 300px etc, so
x += 10;
ends up being
300px10
so replace
var x=item.style.top;
with
var x = parseInt( item.style.top, 10 );
the same goes for setting styles
element.style.top = x + 'px';
You'll have to use a string with units, and to make the CSS actually do something, the elements must be positioned
FIDDLE