How do I use JavaScript variables as a parameter in a jQuery selector?
<script type="text/javascript">
$(function(){
$("input").click(function(){
var x = $(this).attr("name");
$("input[id=x]").hide();
});
});
</script>
<input type="text" id="bx"/><input type="button" name="bx"/>
<input type="text" id="by"/><input type="button" name="by"/>
Basically what I want to do is to be able to hide the element which has an id that is equal to the name of the element that is being clicked.
var name = this.name;
$("input[name=" + name + "]").hide();
OR you can do something like this.
var id = this.id;
$('#' + id).hide();
OR you can give some effect also.
$("#" + this.id).slideUp();
If you want to remove the entire element permanently form the page.
$("#" + this.id).remove();
You can also use it in this also.
$("#" + this.id).slideUp('slow', function (){
$("#" + this.id).remove();
});
$(`input[id="${this.name}"]`).hide();
As you're using an ID, this would perform better
$(`#${this.name}`).hide();
I highly recommend being more specific with your approach to hiding elements via button clicks. I would opt for using data-attributes instead. For example
<input id="bx" type="text">
<button type="button" data-target="#bx" data-method="hide">Hide some input</button>
Then, in your JavaScript
// using event delegation so no need to wrap it in .ready()
$(document).on('click', 'button[data-target]', function() {
var $this = $(this),
target = $($this.data('target')),
method = $this.data('method') || 'hide';
target[method]();
});
Now you can completely control which element you're targeting and what happens to it via the HTML. For example, you could use data-target=".some-class" and data-method="fadeOut" to fade-out a collection of elements.
$("input").click(function(){
var name = $(this).attr("name");
$('input[name="' + name + '"]').hide();
});
Also works with ID:
var id = $(this).attr("id");
$('input[id="' + id + '"]').hide();
when, (sometimes)
$('input#' + id).hide();
does not work, as it should.
You can even do both:
$('input[name="' + name + '"][id="' + id + '"]').hide();
var x = $(this).attr("name");
$("#" + x).hide();
$("#" + $(this).attr("name")).hide();
ES6 String Template
Here is a simple way if you don't need IE/EDGE support
$(`input[id=${x}]`).hide();
or
$(`input[id=${$(this).attr("name")}]`).hide();
This is a es6 feature called template string
(function($) {
$("input[type=button]").click(function() {
var x = $(this).attr("name");
$(`input[id=${x}]`).toggle(); //use hide instead of toggle
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="bx" />
<input type="button" name="bx" value="1" />
<input type="text" id="by" />
<input type="button" name="by" value="2" />
String Concatenation
If you need IE/EDGE support use
$("#" + $(this).attr("name")).hide();
(function($) {
$("input[type=button]").click(function() {
$("#" + $(this).attr("name")).toggle(); //use hide instead of toggle
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="bx" />
<input type="button" name="bx" value="1" />
<input type="text" id="by" />
<input type="button" name="by" value="2" />
Selector in DOM as data attribute
This is my preferred way as it makes you code really DRY
// HTML
<input type="text" id="bx" />
<input type="button" data-input-sel="#bx" value="1" class="js-hide-onclick"/>
//JS
$($(this).data("input-sel")).hide();
(function($) {
$(".js-hide-onclick").click(function() {
$($(this).data("input-sel")).toggle(); //use hide instead of toggle
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="bx" />
<input type="button" data-input-sel="#bx" value="1" class="js-hide-onclick" />
<input type="text" id="by" />
<input type="button" data-input-sel="#by" value="2" class="js-hide-onclick" />
Related
I am trying to achieve this:
Currently value has been set on 2 radio buttons.
Once one of the button is selected, the value(attribute) of that button should be assigned to the value of the div with an id.
I am not sure where I am going wrong. Below is the code snippet.
var init_font_one = $('input[id="init-one-name"]'),
init_font_two = $('input[id="init-two-name"]'),
init_id_value = $("#test");
if (init_font_one == 'checked') {
init_id_value.val(init_font_one.val());
}
if (init_font_two == 'checked') {
init_id_value.val(init_font_two.val());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="test" value="abc"> Testing
<input id="init-one-name" type="radio" name="init-one-name" value="abcd"><label>Test1</label>
<input id="init-two-name" type="radio" name="init-one-name" value="xyz"><label>Test2</label>
You have to use on('change' to update the value of div when radio button is click. And use attr of jQuery to update the value of particular element.
Try this.
var init_font_one = $('input[id="init-one-name"]'),
init_font_two = $('input[id="init-two-name"]'),
init_id_value = $("#test");
init_font_one.change(function() {
init_id_value.attr("value",init_font_one.val());
console.log(init_id_value.attr("value"));
});
init_font_two.on('change',function() {
init_id_value.attr("value",init_font_two.val());
console.log(init_id_value.attr("value"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test" value="abc">
Testing
</div>
<input id="init-one-name" type="radio" name="init-one-name" value="abcd"><label>Test1</label>
<input id="init-two-name" type="radio" name="init-one-name" value="xyz"><label>Test2</label>
There is few problems with your code:
<div> can't have value property.
Your code executes on page load and not when some event was triggered.
init_font_one == 'checked' compares jQuery object with string.
input[id="init-one-name"] can be replaced with #init-one-name
Your labels are not linked with inputs.
$('.radios').change(function() {
$("#test").val($('.radios:checked').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<!-- uncomment below -->
<!--<input type="hidden" id="test" value="abc"/>-->
<input type="text" id="test" value="abc" /> Testing
</div>
<input class="radios" id="init-one-name" type="radio" name="init-one-name" value="abcd"><label for="init-one-name">Test1</label>
<input class="radios" id="init-two-name" type="radio" name="init-one-name" value="xyz"><label for="init-two-name">Test2</label>
You should use jQuery change event to detect the change in the radio buttons and assign the value of checked radio button to the div with id="test"
var init_id_value = $("#test");
$('input[id="init-one-name"]').on('change', function() {
init_id_value.text($(this).val());
});
$('input[id="init-two-name"]').on('change', function() {
init_id_value.text($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test" value="abc">
Testing
</div>
<input id="init-one-name" type="radio" name="init-one-name" value="abcd"><label>Test1</label>
<input id="init-two-name" type="radio" name="init-one-name" value="xyz"><label>Test2</label>
try this
$(document).ready(function(){
$("input[type='button']").click(function(){
var radioValue =
$("input[name='init-one-name']:checked").val();
if(radioValue){
alert("Your are a - " + radioValue);
}
});
});
I do not understand what you are trying to do, but try this:
$( "input[name='init-one-name']" ).change(function(){
$('#test').val('New Value: ' + $(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="test">Testing
</textarea><BR>
<input type="radio" name="init-one-name" value="abcd"><label>Op 1</label>
<input type="radio" name="init-one-name" value="xyz"><label>OP 2</label>
There is no value on a div, but you can change the text content or you can assing a "virtual value" to the div using .data()
Check the snippet
$(function(){ // On jquery initialize
var idtest = $('#test'); // the target Div
$('input[type="radio"]').on('change',function(){ // change event for the two radio buttons
/*** Method 1 : Using data attribute to assing a value ***/
idtest.data('value',$(this).val()); // Value of the selected radio
/*** Method 2 : Add the value of the selected radio to the text inside the div ***/
idtest.text( $(this).val() ) // Value of the selected radio
//retrieve the setted data value
console.log( idtest.data('value') );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test" value="abc">
Testing
</div>
<input id="init-one-name" type="radio" name="init-one-name" value="abcd"><label>Test1</label>
<input id="init-two-name" type="radio" name="init-one-name" value="xyz"><label>Test2</label>
Refer to the fixed code below.
Added a listener to detect action performed over the radio buttons and changed method to check if radio is checked or not.
let ele = document.getElementById('init-one-div');
ele.addEventListener('click', function(e) {
if ("INPUT" === e.target.nodeName)
checkAndAssign();
});
function checkAndAssign() {
var init_font_one = $('#init-one-name'),
init_font_two = $('#init-two-name'),
init_id_value = $("#test");
if (init_font_one.is(':checked')) {
init_id_value.val(init_font_one.val());
}
if (init_font_two.is(':checked')) {
init_id_value.val(init_font_two.val());
}
//REMOVE below line if you want to remove the line printing the result
init_id_value.html(' Testing [ ' + init_id_value.val() + ' ] ');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test" value="abc">
Testing
</div>
<div id="init-one-div">
<input id="init-one-name" type="radio" name="init-one-name" value="abcd"> <label>Test1</label>
<input id="init-two-name" type="radio" name="init-one-name" value="xyz"> <label>Test2</label>
</div>
I have the following HTML to start with :
<div id="p_scents">
<p>
<label for="p_scnts">Friend n°1</label>
<input type="text" id="p_scnt" size="20" name="name_0" class="form-control" placeholder="Name of your friend" />
<input type="text" id="p_scnt address-input-0" class="form-control" name="address_0" placeholder="Their location"/>
</p>
</div>
<button id="addScnt" type="button">Add a friend</button>
I want to add some extra inputs with jQuery, which I succeed to do thanks to the following script:
$(function() {
var scntDiv = $('#p_scents');
var i = $('#p_scents p').length + 1;
$('#addScnt').click(function() {
$('<p><label for="p_scnts">Friend n°' + i +'</label><input type="text" id="p_scnt" size="20" name="name_' + (i-1) +'" class="form-control" placeholder="Name of your friend" /><input type="text" id="p_scnt address-input-' + (i-1) +'" class="form-control" name="address_' + (i-1) +'" placeholder="Their location"/> <button id="remScnt" type="button">Remove friend</button>').appendTo(scntDiv);
i++;
console.log(i);
return false;
});
$('#remScnt').click(function() {
if( i > 2 ) {
$(this).parent('p').remove();
i--;
}
return false;
});
});
My first piece of code, that checks the click on the #addScnt element and appends a new element on the div, works like a charm.
However, my second piece of code, that checks the click on the #remScnt element and should remove its parent <p> element, doesn't work at all and I can't figure out why. I tried debugging with console.log() but I fail... Any clue would be so much appreciated!
Since remScnt is dynamic you need to delegate click, replace this line:
$('#remScnt').click(function() {
With this one:
$(document).on('click','.remScnt',function() {
BTW, ids has to be unique, make sure to replace id with class instead.
<button class="remScnt"
Below is the html
<input type="text" id="textbox1" />
<input type="text" id="textbox2" />
<input type="text" id="textbox3" />
<input type="text" id="textbox4" />
Change
Change1
We are below code
var textbox = $("input[type='text']");
var textarea = $("<textarea id='textarea' rows='10' cols='35'></textarea>");
$("#change").click(function () {
$("input[type='text']").each(function( index ) {
$(this).hide();
$(textarea).insertAfter(this);
});
});
$("#change1").click(function () {
$('textarea').remove();
$("input[type='text']").show();
});
You don't need to user $() selector for plain HTML like <textarea id='textarea' rows='10' cols='35'></textarea> and also wrong usage of insertAfter, in your case is better to use .after. Here's jsFiddle with solution.
var textbox = $("input[type='text']");
var textarea = "<textarea id='textarea' rows='10' cols='35'></textarea>";
$("#change").click(function () {
$("input[type='text']").each(function( index ) {
$(this).after(textarea);
$(this).hide();
});
});
$("#change1").click(function () {
$('textarea').remove();
$("input[type='text']").show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="textbox" />
<input type="text" id="textbox" />
<input type="text" id="textbox" />
<input type="text" id="textbox" />
Change
Change1
since you are not using textarea id in your code, you can remove it
var textarea = $("<textarea rows='10' cols='35'></textarea>");
since as #guruprasadrao has pointed out, id has to be unique.
secondly when user clicks on change again you might not want to keep adding textareas again, so change it to
$("#change").click(function () {
$("input[type='text']").each(function( index ) {
if ( $(this).next().attr( "type" ) != "text" )
{
$(this).next().remove();
}
$(textarea).insertAfter(this);
$(this).hide();
});
});
No need to iterate through each input .Directly use:
$("#change").click(function () {
$("input[type='text']").after($(textarea));
});
I have this form http://jsfiddle.net/thiswolf/XDsSt/ with four identical inputs and buttons.The problem is,each section is updates its own unique data in the database so when updating,its important the submit button i click updates the database with the input from that section only.
My function is
$(document).ready(function() {
$(".xx").live('click', function(){
alert('clicked');
});
});
How do i make sure the button click is unique to that section?.
Use an ID value instead for each input button. This way, jQuery can identify it like so:
$('#button_tag');
HTML:
<html>
<head></head>
<body>
<section>
<input type="text" value="Town">
<input type="text" value="Mayor">
<input type="text" value="Highway">
<input id="btn1" type="submit" class="xx" value="Submit">
</section>
<section>
<input type="text" value="Town">
<input type="text" value="Mayor">
<input type="text" value="Highway">
<input id="btn2" type="submit" class="xx" value="Submit">
</section>
<section>
<input type="text" value="Town">
<input type="text" value="Mayor">
<input type="text" value="Highway">
<input id="btn3" type="submit" class="xx" value="Submit">
</section>
<section>
<input type="text" value="Town">
<input type="text" value="Mayor">
<input type="text" value="Highway">
<input id="btn4" type="submit" class="xx" value="Submit">
</section>
</body>
</html>
Javascript:
$(document).ready(function () {
$(".xx").live('click', function () {
alert('clicked ' + $(this).attr('id'));
});
});
JsFiddle:
http://jsfiddle.net/XDsSt/7/
Get the corresponding section that button belongs to . Then access the elements inside that. You may use the jQuery closest()/parent()(if only one layer of hierarchy of controls) function for that.
$(document).ready(function() {
$(".xx").live('click', function(e){
e.preventDefault(); //if you want to prevent normal form submit
var item=$(this);
var sectionClicked=item.closest("section");
//Let's alert the first text box
alert(sectionClicked.find("input").first().val());
//do whatever with the items belongs the current section
});
});
Sample : http://jsfiddle.net/XDsSt/8/
I recommend you to switch to jQuery on instead of live as it is deprecated.
$(document).ready(function() {
$(".xx").live('click', function() {
$('section').has(this).find(':input:text').each(function() {
alert( this.value ) ;
});
});
});
Demo
If possible then instead of .live(), use .on() with jQUery 1.7+, because live() is deprecated.
$(document).ready(function() {
$("body").on('click', '.xx', function() {
$('section').has(this).find(':input:text').each(function() {
alert( this.value ) ;
});
});
});
Demo
if id is not an option - I don't understand that , but you can put multiple classes in buttons
<input type="button" class="xx btn1" ... >
$(document).ready(function() {
$(".xx").live('click', function(){ // look into on instead on live
if $(this).hasclass('btn1');{
alert('clicked');
}
});
});
Given the following HTML fragment:
<div class="word">
<input type="text" name="A" />
<input type="text" name="n" />
</div>
<div class="word">
<input type="text" name="E" />
<input type="text" name="x" />
<input type="text" name="a" />
<input type="text" name="m" />
<input type="text" name="p" />
<input type="text" name="l" />
<input type="text" name="e" />
</div>
I'd like to write a jQuery script that would concatenate all the ':text' elements' names in a single string, while adding a space when reaching the end of a 'div.word' element.
For example, given the HTML above, the result would be:
An Example
Using my (very) limited jQuery/javascript skills I managed to find a solution, but it involves dirty for ... in loops, so I'd rather not show it here :-).
I'd like to know what is a more elegant/idiomatic (and probably more concise) solution to this problem.
Here's a DEMO: http://jsfiddle.net/ZRukk/1/
var string = $('.word input').map(function() {
var is_last = $(this).is(':last-child');
return this.name + (is_last ? ' ' : '');
}).toArray().join('');
In modern browsers, you could do it without jQuery like this...
Here's a DEMO: http://jsfiddle.net/ZRukk/4/
var inputs = document.querySelectorAll('.word input');
var string = [].map.call(inputs, function(el) {
return el.name + (!el.nextElementSibling ? ' ' : '');
}).join('');
You can do it like this:
var result = [];
$('.word').each(function() {
$(this).find('input').each(function() {
result.push(this.name);
});
result.push(' ');
});
var answer = $.trim(result.join(''));
Working example here: http://jsfiddle.net/jfriend00/DNWSm/
And, a slightly different way of doing it that is probably faster because it's probably less DOM searching:
var result = [];
var lastParent;
$('.word input').each(function() {
// if starting a new parent, add a word separator
if (lastParent && lastParent != this.parentNode) {
result.push(' ');
}
result.push(this.name);
lastParent = this.parentNode;
});
var answer = result.join('');
Working example here: http://jsfiddle.net/jfriend00/bEBGQ/