Im trying to create a simple function that create span's with an class that equals whatever is piped into the function. These spans fill inside a parent div. I also want to ensure that once a span has been added that another span is not add with that id/class, unless my multiSearchEnabled boolean is true.
Here is some code i've
function createBadge(badge_type) {
var badge_parent_div = $("#badge-column-div");
var badge = "<span class='badge-text " + badge_type + "'>" + badge_type + "</span>";
if (!$(badge_parent_div.find("span").hasClass(badge_type))) {
badge_parent_div.append(badge);
} else {
if (multiSearchEnabled) {
badge_parent_div.append(badge); // Add another Badge, since search contains multiples
}
}
}
However this doesnt seem to work, this function will be ran onKeyUp therefore is why i need to detect if the span already exists for this type, so i dont duplicate it.
Updated based on suggestions
function createBadge(badge_type) {
var badge = "<span class='" + badge_type + "'>" + badge_type + "</span>";
var bHasBadge = $("#badge-column-div").has('.' + badge_type);
if (bHasBadge == false || (bHasBadge && multiSearchEnabled == true))
{
// add it
$("#badge-column-div").append(badge);
}
}
However with the following code, nothing ever get's added. I need it add a badge initially, then only if the multiSearchEnabled boolean is true to add more than one.
has() checks for child controls matching a selector.
function createBadge(sBadgeType)
{
var oBadgeParent = $("#badge-column-div");
var bHasBadge = oBadgeParent.has("span." + sBadgeType)
if (bHasBadge == false || bMultiSearchEnabled)
oBadgeParent.append
(
$("<span class='badge-text " +sBadgeType+ "'>" +sBadgeType+ "</span>")
);
}
Related
I have a div with an id like: comment-box-5 and I want to see using javascript if there is a form inside of it if so remove it if not add it (so it toggles when I call the function). I wrote this piece of code to try to do this:
function reply(id){
console.log(document.getElementById('comment-id-' + id).innerHTML.indexOf(document.getElementById('form-' + id)));
if (document.getElementById('comment-id-' + id).innerHTML.indexOf(document.getElementById('form-' + id))) {
var form = replyFn(id);
document.getElementById('comment-id-' + id).appendChild(form);
} else {
//for toogle effect
document.getElementById('comment-id-' + id).removeChild(document.getElementById("form-" + id));
}
}
And I tried executing it but console.log(document.getElementById('comment-id-' + id).innerHTML.indexOf(document.getElementById('form-' + id))); prints -1 even if there is a form inside.
What am I doing wrong? how can I actually see if there is a form in the div?
You could change your condition to :
if ( document.querySelector('#comment-id-' + id +'>#form-' + id) ) {
//Your if logic
}else{
//Your else logic
}
Snippet :
var id = 1;
if (document.querySelector('#comment-id-' + id + '>#form-' + id)) {
console.log('Remove form');
} else {
console.log('Add form');
}
<div id="comment-id-1">
<form id="form-1"></form>
</div>
Try using contains on the div without innerHTML like below, I changed the code from yours a bit to do the example but it should work for yours as well.
console.log(document.getElementById('comment-id-1').contains(document.getElementById('form-id-1')));
<div id="comment-id-1"><form id="form-id-1"></form></div>
I am making an frombuilder in which on choosing an option value (from 1 to 12) it adds an col-xs-(1-12) class to an div. But when I want to choose an other option to add some different col-xs-(1-12) class previous class doesn't get deleted.
function addGrid() {
console.log("addGrid Called !");
console.log($(".grid_cols").val());
var col_val = $(".grid_cols").val();
console.log("col_val :" + col_val - 1);
if ($(".fb-field-wrapper").find('col-xs' + '-' + col_val)) {
console.log("hasClass ??");
$(".fb-field-wrapper").removeClass('col-xs' + '-' + col_val);
console.log("removed class");
}
else {
$(".fb-field-wrapper").addClass('col-xs' + '-' + col_val);
}
}
You may also:
Use a bit of regex to see if a class of pattern col-xs-<num> exists
If yes, remove it
Add the new class
Here is your code, simplified with the above points.
function addGrid() {
var col_val = $(".grid_cols").val(),
$wrapper = $(".fb-field-wrapper"),
matches = $wrapper.attr("class").match(/col-xs-(\d+)/i);
//See if class 'col-xs-<num>' exists
if (matches !== null) {
//If yes, remove that class
$wrapper.removeClass("col-xs-" + matches[1]);
}
//Add Class
$wrapper.addClass('col-xs' + '-' + col_val);
}
Note: In your code, $(".fb-field-wrapper").find('col-xs' + '-' + col_val) would try to find the children of .fb-field-wrapper with the class col-xs-<num> whereas you wanted to see if that class exists in the wrapper itself. For that, you'd do:
if ( $(".fb-field-wrapper").hasClass('col-xs-' + col_val) ) { ... }
My question is this, if I have an Text html element that looks like...
<a id='1' onmouseover="changeImage('setname/setnumber')">Cardname</a>
Can I retrieve the id (in this case 1) on a mouseover event so that I may use it in javascript to do something else with it.
Not sure if I can do this, but I'm hoping I can. What I have is a bit of javascript code that is taking data from an xml document. I have a list of 500+ cards that I have parsed through and stored by categories that are used often. Here are the relevant functions as they apply to my question.
var Card = function Card(cardName, subTitle, set, number, rarity, promo, node)
{
this.cardName = cardName;
this.subTitle = subTitle;
this.set = set;
this.number = number;
this.rarity = rarity;
this.promo = promo;
this.node = node;
}
Where node is the position within the list of cards, and due to the formatting of the document which I started with contains each card alphabetically by name, rather than numbered logically within sets.
Card.prototype.toLink = function()
{
var txt = "";
this.number;
if (this.promo == 'false')
{
var image = this.set.replace(/ /g, "_") + '/' + this.number;
txt += "<a id='" + this.node + "' onmouseover=changeImage('" + image + "')>";
txt += this.toString() + "</" + "a>";
}
else
{
var image = this.set.replace(/ /g, "_") + '/' + this.rarity + this.number;
var txt = "";
txt += "<a id='" + this.node + "' onmouseover=changeImage('" + image + ')>";
txt += this.toString() + "</a>";
}
return txt;
}
Here is what I am using to populate a list of cards, with names that upon hovering over will display a card image.
function populateList () {
for (i = 0; i<cards.length; i++)
document.getElementById('myList').innerHTML += '<li>'+cards[i].toLink()+</li>;
}
What I am trying to do is retrieve the id of the element with the onmouseover event so that I can retrieve everything that is not being saved to a value.
I realized I can pass the id as part of the changeImage function as a temporary workaround, though it involves rewriting my toLink function and my changeImage function to include a second argument. As a married man, I've enough arguments already and could do with one less per card.
In summary, and I suppose all I needed to ask was this, but is there a way using only javascript and html to retrieve the id of an element, onmouseover, so that I may use it in a function. If you've gotten through my wall of text and code I thank you in advance and would appreciate any insights into my problem.
if I have an Text html element that looks like...
<a id='1' onmouseover="changeImage('setname/setnumber')">Cardname</a>
Can I retrieve the id (in this case 1) on a mouseover event so that I may use it in javascript to do something else with it.
Yes, if you can change the link (and it looks like you can):
<a id='1' onmouseover="changeImage('setname/setnumber', this)">Cardname</a>
Note the new argument this. Within changeImage, you'd get the id like this:
function changeImage(foo, element) {
var id = element.id;
// ...
}
Looking at your code, you'd update this line of toLink:
txt += "<a id='" + this.node + "' onmouseover=changeImage('" + image + ', this)>";
Of course, you could also just put the id in directly:
txt += "<a id='" + this.node + "' onmouseover=changeImage('" + image + ', " + this.node + ")>";
And then changeImage would be:
function changeImage(foo, id) {
// ...
}
I didn't use quotes around it, as these IDs look like numbers. But if it's not reliably a number, use quotes:
txt += "<a id='" + this.node + "' onmouseover=changeImage('" + image + ', '" + this.node + "')>";
feel like im coming here way too often to ask questions but yet again I am stuck. I am attempting to select a textarea and allow myself to edit the text in another textarea, which works fine using textboxs but not with textareas. Every time I click on the div container I am getting an undefined result when looking for the textarea. Below is the code.
jQuery
$(".textAreaContainer").live('click','div', function(){
var divID = this.id;
if ( divID !== "" ){
var lastChar = divID.substr(divID.length - 1);
var t = $('#' + divID ).find(':input');
alert(t.attr('id'));
t = t.clone(false);
t.attr('data-related-field-id', t.attr('id'));
t.attr('id', t.attr('id') + '_Add');
t.attr('data-add-field', 'true');
var text = document.getElementById(divID).innerHTML;
//var textboxId = $('div.textAreaContainer').find('input[type="textArea"]')[lastChar].id;
$('div#placeholder input[type="button"]').hide();
var text = "<p>Please fill out what " + t.attr('id') +" Textarea shall contain</p>";
if ( $('#' + t.attr('id')).length == 0 ) {
$('div#placeholder').html(t);
$('div#placeholder').prepend(text);
}
}
else{
}
});
t.attr('id') should be returning textbox1(or similar) but instead just returns undefined.
I have tried .find(':textarea'),.find('textarea'),.find(text,textArea),.find(':input') and quite a few others that I have found through google but all of them return undefined and I have no idea why. A demo can be found here, http://jsfiddle.net/xYwaw/. Thanks in advance for any help guys, it is appreciated.
EDIT: Below is the code for a very similar example I am using. This does what I want to do but with textboxs instead of textareas.
$('#textAdd').live('click',function() {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Textbox " + textBoxCounter + " <br><div id='container" + counter + "' class='container'><li><input type='text' id='textBox" + textBoxCounter +"' name='textBox" + textBoxCounter + "'></li></div></br>";
document.getElementById("identifier").appendChild(newdiv);
textBoxCounter++
counter++;
});
$(".container").live('click','div', function(){
var divID = this.id;
if ( divID !== "" ){
var lastChar = divID.substr(divID.length - 1);
var t = $('#' + divID).find('input');
alert(divID);
t = t.clone(false);
t.attr('data-related-field-id', t.attr('id'));
alert(t.attr('id'));
t.attr('id', t.attr('id') + '_Add');
t.attr('data-add-field', 'true');
var text = document.getElementById(divID).innerHTML;
// var textboxId = $('div.container').find('input[type="text"]')[lastChar].id;
$('div#placeholder input[type="button"]').hide();
var text = "<p>Please fill out what " + t.attr('id') +" textbox shall contain</p>";
if ( $('#' + t.attr('id')).length == 0 ) {
$('div#placeholder').html(t);
$('div#placeholder').prepend(text);
}
}
else{
}
});
First up remove the second parameter, 'div', from the first line:
$(".textAreaContainer").live('click','div', function(){
...to make it:
$(".textAreaContainer").live('click', function(){
Then change:
var t = $('#' + divID ).find(':input');
...to:
var t = $(this).find(':input');
Because you already know that this is the container so there's no need to select it again by id. Also the id attributes that you're assigning to your textarea containers have a space in them, which is invalid and results in your original code trying to select the element with '#textAreaContainer 0' which actually looks for a 0 tag that is a descendant of #textAreaContainer. So fixing the code that creates the elements to remove that space in the id is both a good idea in general and an alternative way of fixing this problem.
I have a div containing a group of divs.
I want the divs inside to work as links that move to another page after saving this link's value.
The div consists of the id in the div attribute, & the name in the div's value as follows:
Html:
<div id="ClasssesList" ></div>
jQuery:
function GetClassesList(data) {
var classes = (typeof data) == 'string' ? eval('(' + data + ')') : data;
$('#ClasssesList').empty();
for (var i = 0; i < classes.length; i++) {
var text = '<button class="BigDiv" value="' + classes[i].Cls_ID + '" >' + classes[i].Cls_Name + '</button>';
$('#ClasssesList').append(text);
}
}
I want to save the value of the clicked id in a localStorage then move to the next page:
I tried to make it as follows, but it doesn't seem to be working:
$("#ClasssesList").bind('click', 'button.BigDiv',CallLink());
function CallLink(e) {
localStorage['ClassID'] = $('Button.BigDiv').attr('value');
window.location.replace("Teacher_Attendance.htm");
}
Do you know what should I do to let it work ?
function CallLink(e) {
localStorage.setItem('ClassID', $('Button.BigDiv').attr('value'));
window.location.replace("Teacher_Attendance.htm");
}
And to get that item try:
localStorage.getItem('classID');
Format to set data to localStorage is
localStorage.setItem(key, value);
here value is string format;
you will get more here Microsoft, Mozilla and Apple.
And one note
I think your bind function
$("#ClasssesList").bind('click', 'button.BigDiv',CallLink())
should be written as
$("#ClasssesList").on('click', 'button.BigDiv',CallLink())