How to use jquery to add numbers to input ID name - javascript

I am using a wordpress plugin that is generating a input field with a given ID name - fieldname15_6
Im using the code in a loop though so for each post it is creating that input field with the same ID name. Of course this is a problem. I have about 10 inputs with the same ID name and I believe it's causing issues with the display. The font sizes and spacing seems a little random regardless of my CSS rules.
Any how, I need a way to automatically add numbers 1+ to any of the created inputs with that ID name. I tried using the following code but it does nothing --
$("input[id^='fieldname15_6']").attr('id', function (i) {
return "fieldname15_6" + ++i;
});
What am I doing wrong?
Thanks.

var i = 1;
$("input#fieldname15_6").each(function(){
$(this).attr('id', function(i) {
return "fieldname15_6" + ++i;
});
});
This will help you.....

$("input[id^='fieldname15_6']").each(function(i){
$(this).attr('id', $(this).attr('id') + i);
});

Try this:
var $files = $('body').find("input").attr("id","fieldname15_6");
$files.each(function(index)
{
newIndex = $(this).attr("id") + index;
$(this).attr("class", newIndex );
});

The simple answer is Don't. You should use classes for this type of thing, that's what they are for. Then you can use various methods to target and work with the individual elements like .eq()
$('#result').html($('.fieldname15_6').eq(2).val()); // eq is 0 based array syntax so 2 will be the 3rd element
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="fieldname15_6" value="first value">
<input type="text" class="fieldname15_6" value="second value">
<input type="text" class="fieldname15_6" value="third value">
<br>
<br>
<br>
<br>
<div id="result"></div>

Related

Accessing Input element through input name in javascript

I want to access the following code using java script. Can anyone help me please? I'm a beginner to JavaScript.
<input type="text" name="username" />
I wish to access the element from its name property. An alert box needs to be shown if the length of element value is less than 6.
Use getElementsByName() method,
document.getElementsByName('username')
getElementsByName() returns an array of elements.
The getElementsByName() method returns a collection of all elements in the document with the specified name
var x = document.getElementsByName("username")[0].tagName;
Its better you can use id instead of name if it is unique.
<input type="text" id="username" />
var x=document.getElementById("username");
Try using document.getElementById(), need to specify unique id
var usrtxt = document.getElementById('usrtxt');
alert(usrtxt.name + ": " + usrtxt.value);
<input type="text" name="username" id='usrtxt' value='admin' />
Try using document.getElementsByTagName()
var inputArray = document.getElementsByTagName('input');//gives array
var usrtxt = inputArray[0];//get first element
alert(usrtxt.name + ": " + usrtxt.value);
<input type="text" name="username" value='admin' />
Probably the input is in a form like:
<form ...>
<input name="username">
...
</form>
and probably you want to validate it when the form is submitted, so in that case you likely have a listener on the form like:
<form onsubmit="return validate(this)" ...>
and in the validate function:
function validate(form) {
// get input as form.username
if (form.username.value.length < 6) {
alert('Username must be 6 or more characters long');
// Prevent form submission
return false;
}
}
You may want to be more sophisticated with the UI (your users will appreciate it), but the above shows the basics.
If you wish to identify particular element using Name then use getElementsByName function
Javascript:
var x = document.getElementsByName('username');
If you consider to use the Jquery then please use following code.
Jquery:
$('[name="username"]');
Learn more about Jquery Selectors
Update:
var x = document.getElementsByName('username'); // X is an array here as getElementsByName returns collection i.e. Array
var val = x[0];//get first element
if(val.value.length < 6) // Check if its value greater than 6
{
alert('boom !!');
}
}

Modify the value of each textfield based on original value using jQuery

Is it possible to modify the value of each textfield present in a webpage, based on the original value, using jQuery or JavaScript?
For example, suppose I have 50 textfields in a page. I want to remove whitespace from the beginning and end of each textfield’s value. I don’t find it to be a good idea to call the function for every textfield individually. How can I do it without calling a function for each textfield?
Can just use val() with a callback argument. It will loop over all elements for you:
$('input[type=text]').val(function( index, originalValue){
return $.trim(originalValue);
});
val() API docs
You can execute this code:
$('input[type=text]').each(function (i, e) {
var $this = $(e);
$this.val($this.val().trim());
});
Get all the inputs from the page using jquery then run a loop, and for each element trim the value
<body>
<input type="text" value=" abc " >
<input type="text" value=" def " >
<input type="button" id="remove" value="Remove">
<script type="text/javascript">
$(document).ready(function(){
$('#remove').click(function(){
var inputs = $('input[type=text]');
$.each(inputs, function(index,input){
$(input).val($(input).val().trim())
});
});
});
</script>
</body>

Updated HTML from JavaScript variable

im trying to build a form with a few number type inputs that the users picks and one checkbox.
im not using php its all java cause im trying to count a bill using his inputs and print out the result.
how do i print those variables? document.write wont do cause its immidetly prints the var without the calculation.
here is some of the script (which is nothing):
$(document).ready(function(e) {
$('.content_window').css('height','900');
$('#top').css('float','none');
var shutter_price
shutter_price = ($('#shutter').val())*200;
if (shutter != '0' )
write(shutter_price);
});
and the form's input:
<label for="shutter">shutter </label>
<input style="margin-right:98px" name="shutter" type="number" id="shutter">
any suggestions?
Instead of document.write it would be better to update or add an element on the page.
For example, modifying your provided code and markup:
Javascript (jQuery)
$(document).ready(function(e) {
$('.content_window').css('height','900');
$('#top').css('float','none');
$('#shutter').on("change", function(e) {
var shutter_price = $(this).val()*200;
if (shutter_price >= 0) {
$('#shutter-result').text(shutter_price);
}
});
});
HTML
<label for="shutter">shutter </label>
<input style="margin-right:98px" name="shutter" type="number" id="shutter" min="0" step="1" pattern="\d+" />
<div id="shutter-result"></div>
JSFiddle
I think you can create a div on your HTML,
and use: $('#id_of_div_where_you_want_to_write').html("text you want to write");
p.s. This is javascript
javascript != java o/
Hope it helps bro!
i've typed the whole calculation.
i have a submmision button which by clicking needs to retrive the sum.
it doesnt work... im pretty new at javascript so i cant really tell where is the problem.
here is the code:
$('#home_price').submit(function(){
var shutter_price, lights_price, socket_price, screen10_price, screen7_price, dimmer_price, x
var total_price = 3000;
shutter_price = ($('#shutter').val())*200;
light_price = ($('#lights').val())*200;
socket_price = ($('#socket').val())*200;
screen10_price = ($('#screen10').val())*700;
screen7_price = ($('#screen7').val())*200;
dimmer_price = ($('#dimmer').val())*400;
if($('#boiler').is(":checked")==true){
total_price+=600;
x+=1;
}
x+=($('#shutter').val())*2+($('#lights').val())+($('#socket').val());
Math.floor(x);
x+=1;
total_price = total_price + shutter_price + light_price + socket_price + screen10_price + screen7_price + dimmer_price + x*400;
$('#home_pricing').val()=total_price;
if($('#home_pricing').val() < 6000)
alert('the solution invalid');
else
alert(" total: " + $('#home_pricing').val());
});
});
and a piece of the html code:
<label for="screen7"> 7inch screen </label>
<input style="margin-right:70px" name="screen7" type="number" id="screen7"> <br><br>
<label for="dimmer"> dimmer</label>
<input style="margin-right:174px" name="dimmer" type="number" id="dimmer"> <br><br>
<label for="boiler"> bolier </label>
<input style="margin-right:148px" type="checkbox" name="boiler" id="boiler" > <br><br>
<div>
<input type="submit" name=" home_pricing " id="home_pricing" value=" calculate " >
</div>
</form>
any suggestion of how to make the computation and retrive an alert window or other sort of window with the answer?
tnx
I know you did not say that you are using jquery, but I would highly recommenced it, because it makes javascript a lot easier. If you need to display this value to the user then you can use jquery's html function. Here is the link, https://api.jquery.com/html/. I would just write the value to a div that's is suppose to display the answer.
Let me know if you need it, and I can give you a quick plunker.

How can I count the total number of inputs with values on a page?

I'm hoping for a super simple validation script that matches total inputs on a form to total inputs with values on a form. Can you help explain why the following doesn't work, and suggest a working solution?
Fiddle: http://jsfiddle.net/d7DDu/
Fill out one or more of the inputs and click "submit". I want to see the number of filled out inputs as the result. So far it only shows 0.
HTML:
<input type="text" name="one">
<input type="text" name="two">
<input type="text" name="three">
<textarea name="four"></textarea>
<button id="btn-submit">Submit</button>
<div id="count"></div>
JS:
$('#btn-submit').bind('click', function() {
var filledInputs = $(':input[value]').length;
$('#count').html(filledInputs);
});
[value] refers to the value attribute, which is very different to the value property.
The property is updated as you type, the attribute stays the same. This means you can do elem.value = elem.getAttribute("value") to "reset" a form element, by the way.
Personally, I'd do something like this:
var filledInputs = $(':input').filter(function() {return !!this.value;}).length;
Try this: http://jsfiddle.net/justincook/d7DDu/1/
$('#btn-submit').bind('click', function() {
var x = 0;
$(':input').each(function(){
if(this.value.length > 0){ x++; };
});
$('#count').html(x);
});

jquery remove not removing

so I've got this form:
<form id="imageinputpopup" class=suggestionsubmit style="display: none">
<span>Add a thing!</span><br/>
<label>url: </label><input name="imageurl" type="url"><br/>
<label>file: </label><input name="imagefile" type="file"><br/>
<input type='hidden' name='schoolid' class="schoolid">
<input type="submit" value="Submit">
</form>
and this click handler:
$(".allow-submission").live('click', function(){
if($(this).attr('inputtype')=="colorpicker"){
....
} else if($(this).attr('inputtype')=="image"){
remove_hidden("#imageinputpopup");
add_fieldname($(this), $("#imageinputpopup"));
$("#imageinputpopup").dialog();
} ....
});
remove_hidden looks like:
function remove_hidden(element){
alert($(element).children('.fieldname').length);
$(element+'.fieldname').remove();
alert($(element).children('.fieldname').length);
}
and add_fieldname looks like:
function add_fieldname(element, addto){
var elementname = document.createElement('input');
elementname.type = 'hidden';
elementname.name = 'fieldname';
elementname.value = element.attr('fieldname').replace(' ', '_');
$(elementname).addClass('fieldname');
addto.append(elementname);
}
as I expect, with each click, a tag like this is added:
<input type="hidden" name="fieldname" value="mascot_image" class="fieldname">
but remove_hidden isn't removing!
I know the selector is right because the alert is exactly the number of these input tags, but they're just not getting removed. Why? I also tried $(element+).remove('.fieldname'); and that didn't work either.
In this line of remove_hidden
//Select the element with the id of element AND has the class of fieldname
$(element+'.fieldname').remove();
Try putting a space before the . like so:
//Select the children of element which have a class of fieldname
$(element+' .fieldname').remove();
EDIT: Added comments above to clear things up a bit
If I get this source right, on one hand you don't have an ID on the input you get when you add a fieldname with the add_fieldname function. You might want to set that for ease of use.
On the other hand, in the remove_hidden function you alert out the element .fieldname, but trying to remove the element.fieldname (notice the missing space in front of the class name), so I presume you need this in the remove_hidden function:
$(element+' .fieldname').remove();
I hope it helps.
try replacing
$(element+'.fieldname').remove();
with
$(element+' .fieldname').remove();
It's because .remove([selector]) "filters the set of matched elements" to decide what to remove.
Their documentation threw me off at first. What you are trying to remove already needs to be in the collection (no selector in the remove method would remove the entire collection).
Ex: Remove input.fieldname:
$(element).find('.fieldname').remove('.fieldname');
or (for the larger case collection case):
$(element).find('input').remove('.fieldname');
Ex: Do NOT remove input.fieldname:
$(element).find('input').remove('.notfieldname');

Categories

Resources