I have a div which is
<div class="add1"></div>
I want the add1 become add+thenumber of length example:
var n= $('.add1').length + 1;
$('.add1').click(function(){
so what I did is
$('.add+n').click(function(){
but it doesnt work, please help me :(
You can store the number in a data attribute and increment on every click.
Change the class attribute from the data attribute value.
HTML
<div id="myDiv" data-num='1' class="add1">click me</div>
JS
document.getElementById('myDiv').addEventListener('click', function(){
var num = Number(this.getAttribute('data-num'));
num++;
this.setAttribute('data-num', num)
this.setAttribute('class', 'add' + num);
});
Try this
$('.add'+n).click(function(){
});
the n needs to be outside of the quotes else it will interpret it as a string. Like so:
$('.add' + n).click(function(){
At first i read your question wrong and i thought you wanted to change the div's class accordingly. Which you could do like this:
var n = 1;
var n= $('.add'+1).length + 1;
$('.add' + n).click(function(){
$(this).attr('class', 'add' + n); //for if you also want to change the class of the div
});
Make use of .addClass() to add and .removeClass() to remove classes
$('.add1').click(function(){
var n= $('.add1').length + 1; //reads n
$(".add1").addClass("add"+n); //adds new class
$(".add"+n).removeClass("add1"); //removes existing class
});
Here is the example: https://jsfiddle.net/danimvijay/ssfucy6q/
If you want to select the class with combination of a variable, use $('.add'+n) instead of $('.add+n').
$('.add'+n).click(function(){
//place code here
});
Here is the example: http://jsfiddle.net/danimvijay/a0j4Latq/
Here it is!! try this .. I code following exactly you need.
<input type="text" style="display:none;" name="qty" value="0" />
<p id="inc" class="">It's class will be Increased[concate with number]</p>
<input type="button" id="btn" name="btn" value="increase"/>
Now following is Main script that will help you ..
var incrementVar = 0;
$(function() {
$("#btn").click(function() {
var value = parseInt($(":text[name='qty']").val()) + 1;
$(":text[name='qty']").val(value);
$('#inc').removeClass('a' + (value-1));
$('#inc').addClass('a' + value); // I believe class names cannot start with a number
incrementVar = incrementVar + value;
});
});
i posted this code also on www.codedownload.in
Thank You.
Related
Hi I'm just new to Javascript and I am trying to assign a value to a variable coming from the input box then access that variable in a loop. I have tried using document.getElementbyID('inputboxID').value; and document.getElementbyName('inputboxName').value; but it didn't work.
Here's my code:
<script>
var count = 0;
$(function(){
$('p#add_field').click(function() {
var num = document.getElementById('enfonum').value;
while (count < num) {
count +=1;
$('#container').append(
'<strong>Enforcer #'+count+'</strong><br/>'
+'<input id="field_ '+count+'"name="field[]'+'"type="text"/><br/>');
}
});
});
}
</script>
Here's the code for the input box:
<input type="text" id="enfonum" name="enfotxt"/>
and here's the code for the link that will trigger the script to be executed:
<p id="add_field">< a href="#"><span>» Add Enforcer</span></a></p>
You have to get value of enfonum input at run-time, not storing it at num var during initial page loading.
Here is the working sample with correct code:
var count = 0;
var num = document.getElementById('enfonum');
$('p#add_field').click(function () {
while (count < num.value) {
count += 1;
$('#container').append('<p><strong>Enforcer #' + count + '</strong><br/>'
+ '<input id="field_' + count + '" name="field[]' + ' "type="text"/><br/></p>');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><input type="text" id="enfonum" name="enfotxt" /></p>
<p id="add_field"><span>» Add Enforcer</span></p>
<div id="container"></div>
The reason your code is not working, is simply that document.GetElementById does not exists, the correct syntax is document.getElementById.
Here's a jsfiddle with an example.
Good luck and good continuation,
Cheers !
Remove the extra } in the code, it will give you syntax error.
Tried it afterwards,the code works.
Syntax errors can break your javascript, it is wise to use plugins like firebug for firefox to fish out javascript errors.
Let me know if it works.
I auto genrated some buttons
<div class="wrapper" id="wrapper"></div>
<script type="application/javascript">
var x, i, y;
for(i = 0; i <= 10; i++){
y = i;
x = "<button class=btn_class"+y+"id=btn"+y+"onclick(alert(this.id);>Ukor</button>";
$("#wrapper").append(x);
}
$("button").on("click", function(){
alert(this.id);
});
</script>
I want to be perform different action when any of the buttons are clicked.
but i can't seem to get get the buttons by id. I also need to send y as an arguement to the function
The problem is that you have no spaces separating the attributes. So you're creating an element that looks like:
<button class=btnclass0id=btn0onclick(alert(this.id);>Ukor</button>
So everything is going into the class attribute. You should put quotes around the attribute values, and spaces between the attributes.
There's also no need for the onclick attribute, since you're using $("button").on("click", ...) to do that.
So it should be:
x = "<button class='btn_class"+y+"' id='btn"+y+"'>Ukor</button>";
You can also use jQuery's object-oriented way to create elements:
x = $("<button>", {
"class": "btn_class" + y,
"id": "btn"+y,
text: "Ukor"
});
BTW, why do you put y in the class? Usually the point of classes is to have all the similar elements have the same class, so you can address them all at once.
It looks like you are building your HTML without the necessary spaces or punctuation between attributes, so your button HTML will look like this:
<button class=btn_class0id=btn0onclick(alert(this.id);>Ukor</button>
This means there is no id attribute.
Try fixing it up like this:
x = '<button class="btn_class' + y + '" id="btn' + y + '" onclick="alert(this.id);">Ukor</button>';
$("#wrapper").append(x);
...or better yet, use the jQuery API to build your DOM:
x = $('<button onclick="alert(this.id);">Ukor</button>').attr({
id: 'btn' + y,
className: 'btn_class' + y
});
Your problem is in the string formatting your code will generate
<button class=btnclass0id=btn0onclick(alert(this.id);>Ukor</button>
and you need:
<button class="btnclass0" id="btn0" onclick="alert(this.id);">Ukor</button>
var x, i, y;
for (i = 0; i <= 10; i++) {
y = i;
x = "<button class='btn_class" + y + "' id='btn" + y + "'>Ukor</button>";
$("#wrapper").append(x);
}
$("button").on("click", function() {
alert(this.id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper" id="wrapper"></div>
Add the content into a single string and then append it once into the dom - faster than appending each iteration. Then using a designated click event handler - alert the id of the button. And the classes need to be a common value - not unique like the id's. Also - you don't need "y" at all and if you need to send the number to a function you have it already in the id - just get the numerical portion of the id and you can use it as required.
$(document).ready(function(){
var x="";
for(i = 0; i <= 10; i++){
x += "<button class='btn_class' id='btn"+i+"'>Ukor</button> ";
}
$("#wrapper").append(x);
$(document).on('click','.btn_class', function(){
(alert($(this).attr('id')))
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper" id="wrapper"></div>
I recommend to use String template to avoid errors of spacing between attrs on concatenating -> Better in visibility of variables in String:
$(Array.from({length:11},(v,k)=>k)
.map((i)=>`<button class="btn_class${i}" id="btn${i}" onclick="alert(this.id)">Ukor${i}</button>`)
.join('')).appendTo('#wrapper')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper" id="wrapper"></div>
I have to add an id to an element. An engine generates the HTML... I have no access to it. It generates random IDs as such:
<input id="5352Adkdie4929888a">
I want to grab the first instance of "<input id=" and replace the ID it has with
the ID it has + DatePicker.
Example:
<input id="5352Adkdie4929888a DatePicker">
How would I go about doing this?
My code so far:
function addID(){
var html= document.documentElement.innerHTML;
var start= '<input id="';
var end= '"'
var htmlIWant=html.substring(html.indexOf(start) + start.length), html.indexOf(end)-1 + 'DatePicker';
}
Am I on the right track? How do I actually replace the HTML? Thanks!
This is a pure javascript solution as per your requirements.
Assuming that your page will have many input tags and some of them will be without ID attribute below is a solution you can try.
var elements = document.getElementsByTagName("input");
for (var i = 0; i < elements.length; i++)
{
if (elements[i].type == "text" && elements[i].hasAttribute("id"))
{
var id = elements[i].getAttribute("id");
elements[i].setAttribute("id", id + "10");
break;
}
}
Grab the first input inside the element using
$('input:first-child').attr('id','whateverIdName');
If you have to catch first input box that has id attribute, you should do :
$("input[id]")[0]
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I have an input box and a go button. When the user clicks the go button I want to compare the inserted value with another value. I am trying to acquire the input value inside a function like so
function getInput(){
var entry ='';
$('button.go').on('click',function(){
var entry = $(this).siblings('.input').val();
//return entry
})
return entry
}
Basically I want to return the var entry that has an input value, so I could compare the values later in the code
var input = getInput() // this should have input value
is input > othervalue
I call getInput inside document.ready()
You are doing everything right . There are some scope related issues that is not helping you to get the expected result . My suggestion would be to define othervalue variable as global and check it inside the function like this
function getInput(){
$('button.go').on('click',function(){
var entry = $(this).siblings('.input').val();
if(entry>othervalue) //your code
});
}
I am not sure why you are binding dynamic click event inside a function . If there is nothing else you need to do here except this part, then wrap this piece of code inside document.ready.
I would suggest to declare your var entry =''; globally and assign it before comparing.
var entry="";
$('button.go').on('click',function(){
entry = $(this).siblings('.input').val();
});
//do the comparing..
You should do the comparing, after delegating the click function, inside the function.
var entry = "";
$('button.go').on('click', function(){
var entry = $(this).prev('.input').val();
if (entry < x)
// Do something
});
It remains unclear to me what you want to accomplish.
I made some code that might be somewhere near what you want.
jQuery().ready(function()
{
var startValue = $('input[name="the_input"]').val();
$('form').submit(function()
{
var currentValue = $('input[name="the_input"]').val();
$('body').append('<br />' + startValue + ' - ' + currentValue + ' = ' + (startValue - currentValue));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="#" method="post">
<input type="text" value="10" name="the_input" /><br />
<input type="submit" value="go!" />
</form>
how can concatenate the set variable in a for loop to be use as name in an input to get the value?
<script>
var k=0;
var counter = 50;
for(k=0; k<=counter; k++){
var choices = $('input[name=choices'+ k]).val();
var choices = choices.replace(/\ /g, '%');
var choices_ = choices_ +";"+ choices;
}
alert(choices);
</script>
there are multiple input field namely choices1,choices2 and so on.
how can i get the value of those fields using for loop?
how can i concatenate the name choices and the variable k?
can you help me solve this problem??
You could always just iterate using a specialized attribute selector and .each():
var choices = $('input[name^="choices"]'), // name starts with "choices"
choices_val = [] // an array!
;
choices.each(function () {
choices_val.push($(this).val().replace(/\ /g, '%'));
});
alert(choices_val.join(';'));
It saves you the overhead (and headache) of having to pick out and mangle a specific attribute value (choices1, choices2, etc) and having to select it out via selector ('cause I'd think that selecting via $(this) is faster than $('input[name="choices1"]')).
You're declaring choices three times, which is invalid and will lead to many errors.
You use each in jQuery, it's identical as for loop.
Say for example you have this HTML:
<input type ="text" name="field1" value="Alpha" />
<input type ="text" name="field2" value="Bravo" />
<input type ="text" name="field3" value="Charlie" />
And here is the js file:
var k = 1;
$('input').each(function(e) {
alert('choices' + k + '=' + $(this).val());
k++;
});
Demo here. Hope it helps.
$('input[name=choices'+ k +']').val();
you just forget to put another + sign and single quote.
I think you missed 2 quotes and a +.
$('input[name=choices' + k + ']').val();
add quotes
var choices = $('input[name=choices'+ k + ']').val();
use css selector
$(".className").each(function(){
$(this).myFunction();
})
jQuery.fn.myFunction = function()
var choices = $(this).val();
var choices = choices.replace(/\ /g, '%');
var choices_ = choices_ +";"+ choices;
}