I am trying to use jQuery / javascript to remove a class from a named input element if a checkbox is ticked.
I have several checkboxes, each with a accompanying hidden (on page load) text input field.
The checkbox and text input field are named "question_X" and "question_X_description" respectively. (where X is a number 0 to 100, say)
As such I'm trying to define a variable in my code that is defined as "this element's name"+"_description", and then use that to define the suitable element to remove the class from.
Here is what I've tried:
$('input:checkbox').change(function(){
var x = $(this).attr('name').'_description';
if($(this).is(":checked")) {
$('input[name="x"]').removeClass("hidden");
} else {
$('input[name="x"]').addClass("hidden");
}
});
However, nothing happens when the any checkbox is checked. Am I referencing my variable correctly?
Use your console, It will have error messages.
First issue
var x = $(this).attr('name').'_description';
^^^
That is not how you build a string in JavaScript. JavaScript does not use . to join strings. It uses +
var x = $(this).attr('name') + '_description';
Second issue
$('input[name="x"]').
You are not looking for the string you built, you are looking for an element with the name x
Needs to be
$('input[name="' + x + '"]').
$('input[name="x"]').removeClass("hidden");
Will be looking for:
<input name="x" />
Try
$(name="'+x+'").removeClass("hidden");
Use document.getElementById('element_name')
Example of HTML element:
<input type="text" id="element_name">
Related
I want apply my JS on all my Textarea
$_PAGE->addJSOnLoad("
$('#textarea').keyup(function() {
var nombreCaractere = $(this).val().length;
var msg = nombreCaractere + ' caractére(s)';
$('#compteur').text(msg);
'<span id=compteur>' 0 caractére(s)'</span>';
});
");
This code is in constructor of my class textarea I wnat call him 1 times for all textarea
You should change the jquery selector from $('#textarea') to $('textarea') so as to target all textarea in the document.
Also you may want to use $('.compteur') in place of $('#compteur') so that your can have multiple counters, one for each textarea. Do not forget to update your html correspondingly
Edit: Please use $(this).find('.compteur') in place of $('.compteur') so that only the counter within the current textarea is affected
$('#textarea')
selects a HTML element with the ID "textarea". So this will be at max one textarea-element. The selector for all textareas would be just
$('textarea')
javscript event handlers can take a parameter (Event), so
$('textarea').keyup(function() {
var nombreCaractere = $(this).val().length;
var msg = nombreCaractere + ' caractére(s)';
// code for display, todo!
}
would put the event handler on every textarea (<textarea>) on your page. However, the display for the character count is a bit more difficult, unless it's one fixed element that scrolls along.
but let's say, your textareas all have an attribute data-charcount="[id]" that has the id of a div or something, that will display the character count.
Then you could replace
// code for display, todo!
with
$("#"+this.dataset.charcount).text(msg); // <- assuming this works
and your example textarea should look like this:
<textarea data-charcount="compteur"></textarea>
<span id="compteur"></span>
please note: every id should only appear once!
edit replace event.target with this, and fixed small error with string concat
Someone knows how can I get all the radiobuttons inside a div? The div has a id as follows
<div id="quest{{ $groups }}" class="quest">
I'm using Laravel, therefore my idea is to get the values inside a div, and put in jQuery something like
var radios = $("input[type='radio'][id^='quest'"+groups+"]");
But this doesn´t work, so I want to know how to get all the radiobuttons inside a div an do a loop inside using .each I think.
I need to duplicate one group of questions and then be able to do a validation, but only works for the first group, the second group is not validated and I´ve checked the id value for each radiobutton and change to previousid_2, and the questionnaire is cloned. Also I want to know how can I reset the values when I clone the questionnaire, because if you have select YES NO YES NO, in the second group when you clone it, those results are selected and the disabled fields too.
You're actually asking for several things. Your code implies you have access to the current group in a variable called groups. so...
1) select all radio inputs within a div:
var div = $("div#quest"+groups);
var radiosBtns = div.find("input[type='radio']");
2) Loop over them, and do some work on each element:
var doSomeWork = function(i,radiobtn){
console.log('the value of radio button #' + i ' is ' + radiobtn.value);
};
$.each(radioBtns,doSomeWork);
3) Duplicate a group of radio buttons:
var fromgroup = $("div#quest"+groups);
var togroup = fromgroup.clone();
var insertionPoint = $('body');
var toGroupId = 'questXXX';
// set the ID so it can be targetted
togroup.prop('id',toGroupId);
// reset radio button values
togroup.find('input[type="radio"]').each(function(){
this.prop('checked',false);
});
togroup.appendTo(insertionPoint);
4) Run validation on a specific group
var validateGroup = function(elements){
// your validation logic goes here
var isValid = false;
$.each(function(){
console.log( this.name, this.value );
});
return isValid;
};
// run the validation on the newly inserted group
var targetElements = $("#"+toGroupId).find("input[type='radio']");
var groupIsValid = validateGroup( targetElements );
You can get all radio buttons and iterate on them like following
$("input[type='radio'][id^='quest']").each(function(){
// add your logic here
});
it's very simple using Id's
To get all the elements starting with "quest" you should use:
$("[id^=quest]")
To get those that end with "jander"
$("[id$=quest]")
and the complete answer is
var radios = $("input[type='radio'][id^='quest']");
the point is what if you want to wildcard class :( :(
$("[class^=quest]")
on a dom like
<pre>
<a class="btn quest primary">link</a>
<pre>
it won't work , thus you will need a more complex wildcard that you have to till me when you find it :D
the fact is you will not need it , whenever you need to get a list of element using classes just use a common class :D
hope i helped u well
I have some input fields that has its id's number changes dynamically.
For example, the below code shows an input field that has "id="field14". The word (field) in the id does not change, but the (number) is changing dynamically. So it may be field14, field13, or field20, etc, and there is no limit for numbers.
<input type="text" name="field[14]" id="field14" value="" size="30" style="height: 24px;">
I'm using the following code to style the input field:
document.getElementById("field14").style.height = "24px";
Note, the application's PHP code is encoded & I'm editing in smarty template.
The input code in the template is like this: {$field.input} So when I inspect element on the live page it shows the above code of the input with the dynamic number of the id.
I want a way that allow me to style any input field of the page that starts with the word (field) and ends with a dynamic (number). Any suggestions please?
For a pure CSS approach, I would check the name instead, so you should only look for input elements whose attribute starts with field[ and ends with a closing bracket ].
e.g.
input[name^="field["][name$="]"] {
...
}
From the code you posted you can reasonably suppose that the name of all the elements containing a numeric index inside brackets [] are also the same elements with that dynamic index as a part of your id.
otherwise you may write a more complex set of selectors looking for an id starting with field and ending with a digit [0..9]
e.g.
input[id^="field"][id$="0"],
input[id^="field"][id$="1"],
input[id^="field"][id$="2"],
input[id^="field"][id$="3"],
input[id^="field"][id$="4"],
input[id^="field"][id$="5"],
input[id^="field"][id$="6"],
input[id^="field"][id$="7"],
input[id^="field"][id$="8"],
input[id^="field"][id$="9"] {
...
}
or even combine both the methods
input[name^="field["][name$="]"][id$="0"],
input[name^="field["][name$="]"][id$="1"],
...
input[name^="field["][name$="]"][id$="9"] {
...
}
You can use an attribute selector:
input[id^=field] {
/* Styles */
}
It will match all input elements whose id attribute begins with "field". Using some separator between "field" and the number may be better to prevent matching things like "fieldone".
input[id^=field] {
background: red;
}
<input id="field1" />
<input id="field2" />
<input id="field3" />
<input id="field15" />
<input id="field99" />
i strongly recommand using a class attribute:
HTML
<input type="text" class="fields" name="field[14]" id="field14" value="" size="30" style="height: 24px;">
CSS
.fields {
/*style*/
}
I want a way that allow me to style any input field of the page that
starts with the word (field) and ends with a dynamic (number). Any
suggestions please?
This is a very specific question that wants us to key on the fact that the id starts with "field" and ends in a dynamic number. IMHO this solution answers your question exactly as asked using only CSS, plus it doesn't require you to change your HTML or add a class attribute (although this would be much better).
This CSS code will find any <input> tag that has an id starting with "field" and ending in a number. It will also exclude those that start with "field" but do not end in a number.
input[id^='field'][id$='0'],input[id^='field'][id$='1'],input[id^='field'][id$='2'],input[id^='field'][id$='3'],input[id^='field'][id$='4'],input[id^='field'][id$='5'],input[id^='field'][id$='6'],input[id^='field'][id$='7'],input[id^='field'][id$='8'],input[id^='field'][id$='9']
{
// styling code
}
Demo code: http://jsfiddle.net/Drakes/7wpnL/671/
If you need JS approach:
http://codepen.io/knitevision1/pen/LEaXxW
var num = 2;
document.getElementById("input" + num).style.backgroundColor = "blue";
If I get you right, you need all your new input look somewhat unique or something.
You can think of getting a number of the currently presenting inputs, then get the last of them, then attach your style based on what you want it to look like.
Using jquery:
var inputs = [];
function getFields(){
$('input').each(function() {
if($(this).attr('id').substring(0,5)=='field'){
inputs.push($(this));
}
});
}
you can modify each input inside the "each" loop, or you can use the "inputs" variable.
Demo: http://jsbin.com/kubaku/1/edit?html,js,output
JS
var inputs = document.getElementsByTagName('input');
var ID = 'field';
var i;
for(i = 0; i < inputs.length; i++) {
var input = inputs[i];
var regex = new RegExp("^" + ID);
if(regex.test(input.id)) {
input.style.border = '1px solid #c00';
}
}
I am counting the number of inputs on the current document that have value. It works fine, except for when I have dynamically added more inputs. I can't get there values.
For example I may have
<input id="participant-1"/>
<input id="participant-2"/>
...
Dynamically created after button click
<input id="participant-15" />
I'll get the value of each one in a for loop like
for(var i =1 ; i <25; i++)
{
...$('input#participant-' + i).val();
}
Now when I run a for loop to check the value of each one of these inputs it only gets the values of the inputs that weren't dynamically created. I have looked at the other questions on here and I still can't see how to apply something like .on() to what I am trying to accomplish.
NEW FOLLOW UP QUESTION
ok, now I think this is where I need more clarification concerning how to use the .on.
I have a jsfiddle here: JsFiddle example
where I create new elements and on blur of all text boxes I would like to calculate how many of the elements have value and log it. Now it currently will respond from blur event with elements who were static. It doesn't work for dynamically created elements
Give it a common class:
<input class="textbox" id="participant-1"/>
<input class="textbox" id="participant-2"/>
And get it like:
var values = [];
$('.textbox').each(function(){
values.push($(this).val());
});
console.log(values)
And to answer the edit:
The Syntax should be : $(container_selector).on(event_type, target_selector, callback)
JSFiddle Demo
$('.name').on('blur', 'input', calculate_total);
Could also consider the use of the CSS attribute selector.
http://www.w3.org/TR/CSS2/selector.html#attribute-selectors
$("input[id|=participant]").each(function(){
// something
});
Using a class selector will save time here.
<input id="participant-1" class="participant"/>
<input id="participant-2" class="participant"/>
Then use a simple count call...
var count = $('.participant').length
alert ('You have ' + count + ' Counted Inputs');
//result is 2
Hope you find this useful
There should be a simple solution for this. I need to get an input element by name and set its value.
The following Javascript does not work:
x = document.getElementsByName($('#questions').val());
x.value=this.value;
Is there a simple solution using JQuery?
Description
You are mixing normal javascript and jQuery.
Use the attribute selector.
Check out my sample and this jsFiddle Demonstration
Sample
Html
<input type="text" name="nameOfTheInputElement"/>
jQuery
$(function() {
$("input[name='nameOfTheInputElement']").val("your value");
});
Edit
If you want, for some reason, change a element which name is a value in another element
then do this. jsFiddle Demonstration
Html
<input type="text" id="questions" value="nameOfTheInputElement"/>
<input type="text" name="nameOfTheInputElement"/>
jQuery
$(function() {
var name = $("#questions").val();
$("input[name='"+name +"']").val("your value");
});
More Information
jQuery - Attribute Equals Selector [name="value"]
jsFiddle Demonstration (first sample)
jsFiddle Demonstration (second sample)
A simple, pure JavaScript (and therefore faster) solution:
var x = document.getElementsByName(document.getElementById('questions').value)[0].value = this.value;
I know jQuery's tagline is 'Write less, do more', and in many cases it is true... many cases !== always, though ;-)
getElementsByName() returns a node-list, so you need to get the first one getElementsByName(...)[0]
But you are already using jQuery, so use it. Read some tutorials about the jQuery selectors
Try this
var q = $("#question").val();
var x = $("input[name='" + q + "']").val();
on the 2nd line, variable q, the name provided in input with id 'question', will be enclosed with ' and could contain any supported characters, like space, :, -, etc
If you need the value of a component regardless of its tag, you can do this:
var x = $("[name='" + q + "']").val();
Consider that this approach $("[name='" + q + "']") can return more than one element, but .val() will return only the value of the first element.
If I'm understanding your question correctly, you want to get an element by name, and the name of the element you're selecting will be specified by some dropdown or text area.
Here's my take on it:
Html
<input type="text" id="enteredName">
<button id="doTheStuff">Do the work</button>
<input name="one" value="One">
<input name="two" value="Two">
jQuery
$('#doTheStuff').click(function(){
var objectOfInterest = $('[name=\'' + $('#enteredName').val() + '\']');
alert(objectOfInterest.val());
});
Working example
Here's another working example using a dropdown to specify the selection name.
$('#form-id input[name="name-input"]').val('your value');