I'm trying to work out a way so that when a string is detected in a class of html, I can get the specific ID. For example, if the string was "Action", I'd like to detect Action from the following Strings in the class "categoryCont", and then work out which ID that was. At the moment, I'm using a JQuery Method that simply checks if the class contains the text:
<button class = "categoryCont" id="1365" onclick="selection = (this.id), setupCategory()">Action and Adventure</button>
<button class = "categoryCont" id="43040" onclick="selection = (this.id), setupCategory()">Comedies</button>
<button class = "categoryCont" id="1568" onclick="selection = (this.id), setupCategory()">Sci-Fi and Fantasy</button>
<button class = "categoryCont" id="43048" onclick="selection = (this.id), setupCategory()">Thrillers</button>
The JQuery:
if($('.categoryCont:contains(text)'))
How can I adapt this code so that it searches each version of the class, and then if it matches the text, it saves the ID for use?
Thanks.
This should work.
$(".categoryCont:contains('Comedies')" ).attr('id');
This demo
Update
To hide the particular element you can do (no need to find id)
$(".categoryCont:contains('Comedies')" ).hide();
Still if you want to apply id selector do this:
var id = $(".categoryCont:contains('Comedies')" ).attr('id');
$("#" + id).hide();
You can also assign the text to a variable.
var text = "Comedies";
$(".categoryCont:contains('" + text + "')" ).attr('id');
Related
I have Bootstrap Table that contains an edit button on each row. I've used a data formatter to make the pass the id of the record over with a data attribute that can be extracted when clicked. When I inspect the element in the console I can see the ID is in the dataset property, but when I try to get it out using element.dataset the console contains an error telling me that the dataset is undefined. It's frustrating because I can see it's there!
Here's my click event:
$(".job-edit").click(function(event) {
var editModal = $("#jobEditModal");
var clicked = $(event.target);
var id = clicked.dataset.jobid;
console.log(id);
event.stopPropagation();
//editModal.modal();
});
And the formatter that sets the button up:
job.editFormatter = function (value) {
return "<button class='btn job-edit text-center' data-jobId='" + value + "'><i class='fa fa-pencil-square-o' aria-hidden='true'></i> Edit</button>";
}
So far I've tried replacing .dataset with .getAttribute(), but that didn't work either, I've also tried changing the casing of jobid to jobId, past that I'm not sure what could be causing the problem.
instead of using dataset you can directly get the jobid by using .data() method of jquery like below.you are getting undefined value for dataset as the clicked variable is a jquery object which does not have a definition for dataset
$(".job-edit").click(function(event) {
var editModal = $("#jobEditModal");
var id = $(this).data("jobid");
console.log(id);
event.stopPropagation();
//editModal.modal();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class='btn job-edit text-center' data-jobId='2'><i class='fa fa-pencil-square-o' aria-hidden='true'></i> Edit</button>
Your issue is because clicked is a jQuery object which has no dataset property.
To fix this you need to use the native element reference:
var id = e.target.dataset.jobid;
Alternatively, use the data() method of the jQuery object:
var id = clicked.data('jobid');
I need to write some html with placeholder used for javascript.
ex:
<span><placeholder data-id="42" data-value="abc"/><span>
Later on, a script will access those placeholders and put content in (next to?) them.
<span><placeholder data-id="42" data-value="abc"><div class="Google"><input type="text" value="abc"/></div><span>
But the placeholder tag doesn't exist. What tag can be used? Using < input type="hidden" .../> all over feels wrong.
Creating Custom tag
var xFoo = document.createElement('placeholder');
xFoo.innerHTML = "TEST";
document.body.appendChild(xFoo);
Output:
<placeholder>TEST</placeholder>
DEMO
Note: However creating hidden input fields with unique ID is good practice.
give your span element an id like,
<span id="placeToAddItem"><span>
and then in jQuery,
$('#placeToAddItem').html('<div class="Google"><input type="text" value="abc"/></div>');
or else
var cloneDiv = $('.Google');
$('#placeToAddItem').html(cloneDiv);
Example
The best way to do this, is using <input type='hidden' id="someId" value=""> tags.
Then you can easily access them by using jQuery, and recall the variable or change it.
var value = $("#someId").val(); to get variable or $("#someId").val(value) to change it.
This complete, no jQuery solution allows you to specify the placeholder/replacement html as a string within the element that will be replaced.
EG HTML:
<div data-placeholder="<div class='Google'><input type='text' value='abc'/></div>"></div>
<div data-placeholder="<div class='Boogle'><input type='text' value='def'/></div>"></div>
<div data-placeholder="<div class='Ooogle'><label>with label <input type='text' value='ghi'/></label></div>"></div>
<span data-placeholder="<em>Post JS</em>">Pre JS</span>
<br />
<button id="test">click me</button>
JS:
Use querySelectorAll to select all elements with the attribute 'data-placeholder' (returns a NodeList)
var placeholders = document.querySelectorAll('[data-placeholder]'); //or by ids, classnames, element type etc
Extend the NodeList prototype with a simple 'each' method that allows us to iterate over the list.
NodeList.prototype.each = function(func) {
for (var i = 0; i < this.length; i++) {
func(this[i]);
}
return this;//return self to maintain chainability
};
Extend the Object prototype with a 'replaceWith' method that replaces the element with a new one created from a html string:
Object.prototype.replaceWith = function(htmlString) {
var temp = document.createElement('div');//create a temporary element
temp.innerHTML = htmlString;//set its innerHTML to htmlString
var newChild = temp.childNodes[0];//(or temp.firstChild) get the inner nodes
this.parentNode.replaceChild(newChild, this);//replace old node with new
return this;//return self to maintain chainability
};
Put it all together:
placeholders.each(function(self){
self.replaceWith(self.dataset.placeholder);//the 'data-placeholder' string
});
Another example but here we only replace one specific element with some hard-coded html on click:
document.getElementById("test").addEventListener('click', function() {
this.replaceWith("<strong>i was a button before</strong>");
}, false);
DEMO: http://jsfiddle.net/sjbnn68e/
use the code below :
var x = document.createElement('placeholder');
x.innerHTML = "example";
document.body.appendChild(x);
I am trying to target an id element using a variable in jquery, like so:
var liked_artist = $('#js-helper-liked-artist').val();
var artist_id = $('#js-helper-artist-id').val();
var target = '#individual' + artist_id + '';
$(target).addClass('individual-heart-hover');
However, this is not targeting the id it should correctly. Any ideas? I've tried it without the empty string at the end as well.
EDIT:
HTML:
<i class="fa fa-heart fa-stack-1x individual-heart" id="individual-{{$artist->id}}"></i>
individual-{{$artist->id}} renders as individual-8
and artist_id is 8 (console.log shows this).
Shouldn't it be var target = '#individual-' + artist_id + '';? Unless it's a typo in your post, I think you are missing the dash.
did you enclose your code in the document ready function?
$(document).ready(function() {
// ....
});
As follows, there is an input element on a web page.
<input type = "text" class="text-input">
When I click it, the Javascript code will append another class attribute value W_input_focussuch as:
<input type = "text" class="text-input W_input_focus">
Well, how can I get the class attribute value except the value appended by the Javascript when I click on the input? I use getAttribute('class') method to retrieve ,but it return all the values include the js appended.
It is an example, actually beforehand I do not know which value is set to class attribute in the html code and which value is appended by js.
And How can I distinguish , Thanks!
I have found a simple answer:
$(input).trigger("blur").attr("class")
There's a classList API available for this kind of cases: https://developer.mozilla.org/en-US/docs/Web/API/Element.classList . Check the link for examples.
It's well supported on browsers except IE (10+): http://caniuse.com/#feat=classlist
..but there's a polyfill for that: https://github.com/eligrey/classList.js
To extend this answer:
What you apparently need is Mutation Events / Observers (https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Mutation_events). And especially DOMAttrModified, which will dispatch when your className is changed (i.e classes are added/removed).
Support is good except on IE(11+) and on Android browsers (4.4+): http://caniuse.com/#feat=mutationobserver
...but fortunately on IE, you can use onpropertychange listener: http://msdn.microsoft.com/en-us/library/ie/ms536956(v=vs.85).aspx.
An Example (tested on Chrome, FF, IE10): http://codepen.io/zvona/pen/eGbur/ --> check console for details.
element.className should provide the class names in string format. You can use String.split(' ') to separate them by spaces (since classes are separated by spaces).
JavaScript (no jQuery):
function getClassNames() {
var element = document.getElementById('spanId');
var classNames = element.className; //String containing all the classes as they are given in the attribute
var classes = classNames.split(' '); //Since classes have to be separated by a whitespace, this will return all 'single' classes
}
HTML:
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="classNames.js"></script>
</head>
<body>
<input type="button" onclick="getClassNames()" value="Get Classnames">
<span id="spanId" class="class1 class2"></span>
</body>
</html>
Every class you add from js it appends after the class name you already have. So you can get the classname, split it in " " and get the first element, which is the class name you had in the start.
Try
HTML:
<input type = "text" class="text-input">
JS:
//ADD SOME CLASSES
$( "input" ).addClass( "W_input_focus" );
$( "input" ).addClass( "class2" );
$( "input" ).addClass( "class3" );
//GET THE CLASS YOU WANT
$( "input" ).click(function() {
var className = $('input').attr('class');
var arr = className.split(' ');
alert(arr[0]);
});
DEMO
With just JS you can try
HTML:
<input id="input" type = "text" class="text-input W_input_focus" onclick="getClass()">
JS:
function getClass(){
var className = document.getElementById('input').getAttribute('class');
var arr = className.split(' ');
alert(arr[0]);
}
DEMO2
i am trying to alert id of a button (which is generated using jquery ) but when i alert its value it not coming right. heres the code
function removeimg(name,btn12){
//make request to remove the name
// $("#" + name).closest('li').remove();
// $("#" + btn12).remove();
// document.getElementById(name).style.display = 'none';
// document.getElementById(btn12).style.display = 'none';
var str = "#" + btn12;
alert(str);
alert($(str).val());
}
here is the link
http://shri-ram.lifekloud.com/pilot/step4.php
when you uplaod a image under the tab "add delete photo" the button is generated
i am trying to alert id of a button
val() does not get the id of an element; val returns the value element.
To get the id of an element, use attr
alert($(str).attr('id'));
Just a stab in the dark from your comment well its not even returning value thts the issue. but the id name is getting displayed correctly
If you have
<input type='button' id='b' value='btn' />
then
alert($('#b').val());
will in fact display btn. That said, if you have
<button id='b'>btn</button>
then nothing will be displayed. But like I said that's just a stab in the dark. It's impossible to know better without the html available (and I'm afraid I don't have time to parse through your site)
You have one meta-character . in your id #btnheader-8878374.png, That is the problem.
Just escape like this
$('.#btnheader-8878374\\.png')
and try you will get your concept working.
Full code,
var str = "#" + btn12;
str = str.replace('.','\\\\');
alert($(str).val());
Your problem is most likely that you do not have the value attribute set on your buttons, thus calling val() returns nothing.
If you want the text of the button just call text().
See jsFiddle
HTML
<button id="btn12">Button 12</button>
JQUERY
var str = "#" + "btn12";
alert( str ); // yields #btn12
alert( $(str).val() ); // yields nothing
alert( $(str).text() ); // yields Button 12