jQuery get data-name as value - javascript

I was previously using
jQuery( "select#colour option:selected" ).each(function() {
value += "colour-" + jQuery( this ).val();
});
This took the selected value from a dropdown and constructed another value with it.
I am now trying to modify this to get the value (data-name) from the following html...
<div class="select-option" data-name="apple">
<div class="select-option selected" data-name="orange">
<div class="select-option" data-name="banana">
Anyone got an similar example they can point me at?

use .data('name') to get the data-name attribute value
$(document).ready(function() {
$('.select-option').each(function() {
var name = $(this).data('name');
console.log(name);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="select-option" data-name="apple">
<div class="select-option selected" data-name="orange">
<div class="select-option" data-name="banana">

var value;
$('.select-option').each(function(){
value+=$(this).attr('data-name'); //or $(this).data('name');
});

Use .data()
jQuery( ".select-option" ).each(function() {
value += "colour-" + jQuery( this ).data("name");
})

Related

jQuery - hide / show divs when checkboxes are checked

I have a jquery function to show or hide divs when certain checkboxes are checked or unchecked and work fine using the "change" function. Therefore, if the checkbox has already been previously checked the corresponding div is not shown. How can I change this code to work?
My code is here:
<script>
jQuery(document).ready(function($) {
$('.my_features').change(function() {
var checkbox = $(this);
if( checkbox.is(':checked') ) {
$( '#' + checkbox.attr('data-name') ).show();
} else {
$( '#' + checkbox.attr('data-name') ).hide();
}
});
});
</script>
This is pretty canonical.
I would use data-id instead of data-name though:
$(function() {
$('.my_features').on("change",function() {
$(`#${this.dataset.id}`).toggle(this.checked);
}).change(); // trigger the change
});
.toggleDiv { display:none}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><input type="checkbox" class="my_features" data-id="div1">Div 1</label>
<label><input type="checkbox" checked class="my_features" data-id="div2">Div 2</label>
<div id="div1" class="toggleDiv">Div1 div</div>
<div id="div2" class="toggleDiv">Div2 div</div>
If you do not like mixing DOM and jQuery access then
$(`#${$(this).data('id')}`).toggle($(this).is(':checked'));
I am assuming your question was how to show/hide the divs for checkboxes that are already checked/unchecked upon loading the page.
You can do this by passing in the same function you are using for change() into the each() method, which will iterate over each checkbox and run the function.
jQuery(document).ready(function($) {
$('.my_features').each(function(){
var checkbox = $(this);
//you can use data() method to get data-* attributes
var name = checkbox.data('name');
if( checkbox.is(':checked') ) {
$( '#' + name ).show();
} else {
$( '#' + name ).hide();
}
});
});
Demo
function update(){
var checkbox = $(this);
var name = checkbox.data('name');
if( checkbox.is(':checked') ) {
$( '#' + name ).show();
} else {
$( '#' + name ).hide();
}
}
//just setup change and each to use the same function
$('.my_features').change(update).each(update);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input class="my_features" type="checkbox" data-name="first" />
<input class="my_features" type="checkbox" data-name="second" checked />
<input class="my_features" type="checkbox" data-name="third" checked />
<input class="my_features" type="checkbox" data-name="fourth" />
</div>
<div id="first">First</div>
<div id="second">Second</div>
<div id="third">Third</div>
<div id="fourth">Fourth</div>
You can use the following to get the data and then show or hide the div based on the checkbox value
$(document).ready(function() {
$('.my_features').on('click', function() {
var checkbox = $(this);
var div = checkbox.data('name');
if (checkbox.is(':checked')) {
$('#' + div).show();
} else {
$('#' + div).hide();
}
});
})
You can see a working fiddle
$(document).ready(function(){
$('.my_features').change(function(){
if(this.checked)
$('#data-name').hide();
else
$('#data-name').show();
});
});
Try this way.
<script>
jQuery(document).ready(function($) {
$('.my_features').each(function() {
$(this).change(function() {
var checkbox = $(this);
if( checkbox.is(':checked') ) {
$( '#' + checkbox.attr('data-name') ).show();
} else {
$( '#' + checkbox.attr('data-name') ).hide();
}
});
});
});

How to check attribute value is equal to oue value and get the value of another attribute in that element?

I want to get the particular data-val value. I receive the index value. I need to get data-val's value that which div's data-ind attibute have that index value.
<div data-ind="1" data-val="A"></div>
<div data-ind="2" data-val="B"></div>
<div data-ind="3" data-val="C"></div>
<div data-ind="4" data-val="D"></div>
<div data-ind="5" data-val="E"></div>
var dataind = 1;
console.log($('div[data-ind=' + dataind + ']').attr('data-val'))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-ind="1" data-val="A"></div>
<div data-ind="2" data-val="B"></div>
<div data-ind="3" data-val="C"></div>
<div data-ind="4" data-val="D"></div>
<div data-ind="5" data-val="E"></div>
use attr selector
Description: Selects elements that have the specified attribute with a value exactly equal to a certain value.
Use data-* selector and .attr() to get data-val as shown :-
var ind = "1";
$("div[data-ind = '" + ind + "']").attr('data-val');
OR use .data() as shown :-
var ind = "1";
$("div[data-ind = '" + ind + "']").data('val');
Try this
$(document).ready(function(){
$.each($("div[data-ind]"),function(k,v){
var val = $(v).attr("data-val");
alert("data-ind="+(k+1)+": "+val);
});
});
It will pop up alert as
data-ind=1: A
https://jsfiddle.net/sum1/bcazbLee/3/
I think this should work:
$(document).ready(function(){
var check = '5';
var value = $('div[data-ind= '+check+']').attr('data-val');
alert(value);
});
Use This:
$.each($("div[data-ind]"),function(){
console.log($(this).attr('data-val'));
alert($(this).attr('data-val'));
});`

Remove clicked id from the input value

I am trying to delete clicked id to remove input value. For example i have this input <input type='hidden' id='uploadvalues' value="8,9"/> you can see the values 8,9 and the button is <div class="delete" id="9"></div> .
When i click the id="9" then the input value 9 should be remove . After clicked id="9" ==> <input type='hidden' id='uploadvalues' value="8"/>
How can i do that anyone can teach me?
Demo from CodeCanyon
<div class="container">
<div class="area">
<div class="image"><img src="https://s-media-cache-ak0.pinimg.com/736x/05/2f/1b/052f1b3a2361eb4f3c1385c1fd4f75ed.jpg"></div>
<div class="delete" id="8"></div>
</div>
<div class="area">
<div class="image"><img src="http://www.wallpapermade.com/images/wallpapers/originals/tip-and-oh-laugh-together-home-2015-movie-wallpaper-4612.jpg"></div>
<div class="delete" id="9"></div>
</div>
<input type='hidden' id='uploadvalues' value="8,9"/>
</div>
JS
$(document).ready(function(){
$("body").on("click", ".delete", function(){
// Remove clicked id from the input value
});
});
One way on the approach you want is
$("body").on("click", ".delete", function(){
var id = this.id, //extract the id from the clicked element
values = $('#uploadvalues').val().split(','), // get the existing values in the #uploadvalues element
remaining = values.filter(function(val){ // filter out the ones equal to the id of the clicked element
return val !== id;
});
$('#uploadvalues').val(remaining.join()); // update the changed values
});
make it
$(document).ready(function(){
$("body").on("click", ".delete", function(){
var val = $(this).attr("id");
var values = $( "#uploadvalues" ).val().split(",");
var valIndex = values.indexOf(val);
if (valIndex > -1)
{
values.splice(valIndex,1);
}
$( "#uploadvalues" ).val( values.join(",") )
});
});
Try to make use of regular expression at this context,
$(document).ready(function() {
$("body").on("click", ".delete", function(){
var id = this.id;
$("#uploadvalues").val(function(val){
return val.replace(new RegExp(id + "\,|\,"+ id +"$"),"")
});
});
});
when you click the delete button, in the callback function grab the id:
var valueToRemove = this.id;
// now you need to look to see if that value is inside the hidden input
var valueToRemove = this.id;
console.log(valueToRemove);
var values = $("#uploadvalues").val();
if(values.indexOf(valueToRemove) >= 0){
$("#uploadvalues").val(values.replace(valueToRemove,""));
}
also its best practice to cache the dom so you dont have to constantly query it.
Is this what you wanted? and this method does not get rid of the comma within the values.

How i can get value form select > option, jquery

I have a problem with get value form select > option.
I make option that:
$.each(response, function(i, element)
{
var nazwaKategori = element.name;
var idKategori = element.id;
$("#kategoria").append("<option>KategoriaID:" + idKategori + ", Nazwa Kategorii:" + nazwaKategori + "</option>");
});
In body:
<form role="form">
<div class="form-group">
<label align="center" for="text">Lista dostępnych kategorii.</label>
<select class="form-control" id="kategoria">
<div id="kategoria">
</div>
</select>
<div id="wypisz"><div>
</div>
</form>
And i get this option:
<script>
$( "#kategoria" ).change(function () {
var str = "";
$( "#kategoria option:selected" ).each(function() {
str += $(this.KategoriaID).val() + " ";
});
$( "#wypisz" ).text( str );
})
.change();
</script>
How i can get only idKategori ? I musc find pattern in get text?
Thanks
Well apart of having a wrong html structure with a div inside a select, when you are creating your dropdown, you could use something like this:
$("#kategoria").append("<option value='"+idKategori+"'>KategoriaID:" + idKategori + ", Nazwa Kategorii:" + nazwaKategori + "</option>");
So every option will have a value and then in the change event you could use this:
$( "#kategoria" ).on("change", function () {
var optionselected = $(this).find(":selected").val();
//HEre you will have you value of the option selected in a variable
console.log(optionselected);
});
I don't know if thats what you wanted, and I don't know if your dropdown creation is working, but your questions is to get value from select option with jquery. Hope this helps

JQuery - Click Submit Button Get Form Value

I have the following function and all i am trying to do is get the value out of the form field.
$( ".searchbutton" ).click(function() {
var tc = $(this).closest("form input[name='searchbox']").val();
alert(tc);
return false;
});
The alert keeps telling me "Undefined". I have treid closest, parent, parents, find, etc. I don't know what im doing wrong. Im clicking the submit button and all i want in return is the value in the search box. Please help.
html
<form action="/index.php" method="get" class="qsearch" >
<input type="text" id="fsearch" name="searchbox" >
<input class="searchbutton" type="submit" value="Submit">
</form>
Try this:
$( ".searchbutton" ).click(function() {
var tc = $(this).closest("form").find("input[name='searchbox']").val();
alert(tc);
return false;
});
Update
Yep, it work with your HTML - see here http://jsfiddle.net/qa6z3n1b/
As alternative - you must use
$( ".searchbutton" ).click(function() {
var tc = $(this).siblings("input[name='searchbox']").val();
alert(tc);
return false;
});
in your case. http://jsfiddle.net/qa6z3n1b/1/
Try easiest way:
<script>
$( ".searchbutton" ).click(function() {
var tc = $('#fsearch').val();
alert(tc);
return false;
});
</script>
How about just using $('input[name="searchbox"]') selector:
$( ".searchbutton" ).click(function() {
var tc = $('input[name="searchbox"]').val();
alert(tc);
return false;
});

Categories