JQuery remove() not working with a two word id - javascript

I have a button <button onclick="takedown()"> take down </button> that creates a H1 and button with the id of the text in my text field and h1 at the end for the h1 and button at the end for the button the button has a onclick onclick="delete()". This is that function
function takedown(){
note = document.getElementById("noteinput").value;
idh1 = note + "h1";
idbutton = note + "button";
idcenter = note + "center";
$('<center id="' + idcenter + '"> <h1 id="' + idh1 + '">' + note + '</h1> <button id="'+ idbutton +'" onclick="deletenote()"> Delete </button> </center>').appendTo("body");
}
For the delete function the remove() works only if the id of the button and the h1 is one word.
function deletenote(){
// First setting
var idbuttondelete = event.target.id;
var idh1delete = idbuttondelete.replace("button", "h1");
// Removing the button, h1,center
$('#' + idbuttondelete).remove();
$('#' + idh1delete).remove();
}
Does anybody know whats wrong or how to use JQuery to delete something if it has a two word id.

This will not behave as expected because ID attribute values cannot contain spaces. Replace the spaces with underscore or some other allowed character:
// don't forget VAR or you will have a global variable (bad)
var note = document.getElementById("noteinput").value.replace(/\s/g, '_');
How string.replace() works

First your replace in the delete function will fail if the user enters the word "button", "center", or "h1" as the javascript replace in the delete will only work on the first instance. To prevent the user from having spaces try the below with the delete function you have:
function takedown(){
var note = document.getElementById("noteinput").value;
var idh1 = "h1" + note.replace(/\s/g, '_');
var idbutton = "button" + note.replace(/\s/g, '_');
var idcenter = "center" + note.replace(/\s/g, '_');
//the above 3 variables will use _ instead of space
$('<center id="' + idcenter + '"> <h1 id="' + idh1 + '">' + note + '</h1> <button id="'+ idbutton +'" onclick="deletenote()"> Delete </button> </center>').appendTo("body");
}
If you do not have control over the ID's and need to do this for a lot of objects you can change them all at once (buttons in this case)
$('button').each(function () {
var id = $(this).attr('id');
id = id.replace(/\s/g, '_');
$(this).attr('id', id);
});
And then you can reference all the buttons by ID using a _ instead of space. Otherwise do as others suggested and use a selector other than ID

Since you're using jQuery, you could try this:
var note = $("#noteinput").val().replace(/\s/g, '_');
idcenter = note + "center";
$('<center id="' + idcenter + '"> <h1>' + note + '</h1> <button id="'+ idbutton +'" onclick="deletenote(idcenter)"> Delete </button> </center>').appendTo("body");
}
function deletenote(id){
$('#' + id).remove();
}
You don't need to individually remove the child elements of your tag. I would also recommend against using the center tag, go with a div and center the contents with CSS rather than using center.
I also refactored your function. It's much better to pass in your values and this way, the function is more resuable and testable

As mentioned in the other answers...spaces in ids is bad practice!
BUT if you really need "two words" in your ids, instead of the query selector $, you can use:-
document.getElementById("doesnt mind spaces").remove();

Related

Getting the id of an html on mouseover with only javascript (no jquery)

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 + "')>";

JQuery .hide() won't hide button suddenly

I have this a button which a user can click on which adds a comment box at the bottom of the page. My button html looks like this:
<input type="button" name="inspection_2895_14045_comment" tabindex="-1" value="+" class="commentBtn" onclick="generateComment('Test', 14045,1, this )">
So as you can see it calls a method called generateComment which looks like this:
function generateComment(name, id, isInspection, button){
//get the current button and hide it
var btn = $("a[name='" + button.name + "'");
btn.hide();//doesn't work
var generatedName = '';
if(isInspection){
generatedName = "comment_" + id;
}
else{
generatedName = "section_" + id;
}
var comment = $('#comments');
var genHtml = '<div class="bigDataDiv">' +
' <label class="commentBoxLabels">' + name + '</label>' +
' x' +
' <textarea rows="4" class="commentBox" name=' + generatedName + ' maxlength="200"></textarea>'
'</div>';
comment.append(genHtml);
$('html,body').animate({
scrollTop: $(".bigDataDiv").offset().top},
'slow');
}
All this method does it hide the button, generate the comment div then scroll to the newly created div. This code worked no problem and used to hide the button but now for some reason it doesn't work and the button still shows up
As neokio pointed out, you forgot the closing ], but you are also selecting an anchor tag, when what you want is an input tag.
var btn = $("input[name='" + button.name + "']");
Since button in your generateComment function is a reference to the button you could just use this to set your btn variable:
var btn = $(button);
Then you don't have to worry about putting strings together to make your selector, or what kind of element the button is. Your hide should work no matter what that way.
You forgot the closing ] ...
var btn = $("a[name='" + button.name + "']");
You're also missing a + before the final '</div>';

Dynamically added textbox with given value not added properly,jquery

I added textbox value as Baker's Basket, Pune, Maharashtra, Indiasd but on click event in textbox it only shows Baker's
I want to display whole text Baker's Basket, Pune, Maharashtra, Indiasd in the textbox.
JS FIDDLE EXAMPLE
// Try to Enter text given bellow
//Baker's Basket, Pune, Maharashtra, Indiasd
$("#clk").on('click', function () {
$("#cnt_div").empty();
var getTxt = $("#txt_n").val();
var addContent = "<input type='text' value=" + getTxt + " />";
$("#cnt_div").append(addContent);
});
without editng addContent variable
Edited:
JS FIDDLE SAMPLE TWO
$("#clk").on('click', function () {
var gData1 = $("#txt_1").val();
var gData2 = $("#txt_2").val();
var gData3 = $("#txt_3").val();
var cnt_1 = "<span class='lbl_normal_mode'>" + gData1 + "</span><input class='txt_edit_mode' value=" + gData1 + " type='text'/>";
var cnt_2 = "<span class='lbl_normal_mode'>" + gData2 + "</span><input class='txt_edit_mode' value=" + gData2 + " type='text'/>";
var cnt_3 = "<span class='lbl_normal_mode'>" + gData3 + "</span><input class='txt_edit_mode' value=" + gData3 + " type='text'/>";
var content_Data = "<div class='chunk_div_holder'><div style='float:left:width:100%'>" + cnt_1 + "</div><div style='float:left:width:100%'>" + cnt_2 + "</div><div style='float:left:width:100%'>" + cnt_3 + "</div></div>";
$(".dynmic_cntt").append(content_Data);
});
You should better append the element and its properties dynamically as an object:
$('<input>', {
type: 'text',
value: $("#txt_n").val()
}).appendTo($("#cnt_div").empty());
This will solve the problem of extra spaces (no quotes for value=Baker's Basket), wrong string escape (if the value will have quotes) for value attribute and other caveats.
N.B.: There is no textbox type for <input> element. It should be text instead.
DEMO: http://jsfiddle.net/ZyMCk/11/
Add the field in two stages:
add the field as you are already
set the value of the field using .val()
It is because you aren't escaping ' single quote.
Instead you can replace
this line
var addContent="<input type='textbox' value='"+getTxt+"' />";
with
var addContent=$("<input type='textbox' />").val(getTxt);
or
var addContent="<input type='textbox' value=\""+getTxt+"\" />";
Value attribute should enclose in quotes. In your case, its better to use double quotes, because Baker's Basket, Pune, Maharashtra, Indiasd already have a single quote in it.
$("#clk").on('click',function(){
$("#cnt_div").empty();
var getTxt=$("#txt_n").val();
var addContent="<input type='textbox' value=\""+getTxt+"\" />";
$("#cnt_div").append(addContent);
});
Fiddle
Edit
$("#clk").on('click',function(){
$("#cnt_div").empty();
var getTxt=$("#txt_n").val();
var addContent=$("<input/>",{type:"text",value:getTxt});
$("#cnt_div").append(addContent);
});
Updated fiddle
change "+getTxt+" to '"+getTxt+"'
fiddle
OR
change "+getTxt+" to \""+getTxt+"\"
Heres a better way of doing this...
var addContent=$("<input type='textbox' />").val(getTxt);
http://jsfiddle.net/ZyMCk/9/
Basically, if creating an element to append to the DOM your better off doing this as a jQuery object. This way we can take advantage of methods such as val() for adding the value.
UPDATE
Ive simplified things a bit for you...
JSFIDDLE: http://jsfiddle.net/ZyMCk/22/
$("#clk").on('click', function () {
$('.dynmic_cntt').empty();
$('.form-text').each(function(){
var $div = $('<div style="float:left:width:100%;"></div>');
var $span = $('<span class="lbl_normal_mode">'+ $(this).val() +'</span><input class="txt_edit_mode" value="'+$(this).val() +'" type="text"/>');
$('.dynmic_cntt').append( $div.append( $span ) );
});
});

javascript function using jquery addClass() method does not add class

The script works, creates everything correctly, etc., but the jquery addClass method isn't adding the class. I'm new to using jquery methods in a javascript function, any help is appreciated, including alternate methods for adding the appropriate classes without using jquery.
function thumbnail(Img, Element, Modal, ModalTitle) {
"use strict";
/*jslint browser:true*/
/*global $, jQuery*/
//this function will append an anchor tag with the appropriate functionality, accepting inputs on the image filename, attaching element, and modal
//Img = full filename in format of foo.png
//Element = the ID of the element within which the thumbnail anchor will be placed
//Modal = the ID of the modal
//ModalTitle = Text used for title of the modal and title of the caption
var image, element, modal, loc, output, iUrl, modal_loc, modal_output, mtitle;
image = Img;
element = Element;
modal = Modal;
mtitle = ModalTitle;
iUrl = "/design-library/images/thumbs/" + image;
output = "<a href='#' data-reveal-id='" + modal + "'>";
output += "<img class='sample_img' src='" + iUrl + "' alt='" + mtitle + "' />";
output += "</a>";
output += "<p class='caption'>" + mtitle + "</p>";
modal_output = "<h1>" + mtitle + "</h1>";
modal_output += "<img src='" + iUrl + "' alt='" + image + "' /><a class='close-reveal-modal'>×</a>";
//create the modal container
$(modal).addClass('reveal-modal');
modal_loc = document.getElementById(modal);
modal_loc.innerHTML = modal_output;
//the end of the script gets the element and adds the anchor tag that exists in output
$(element).addClass('samples');
loc = document.getElementById(element);
loc.innerHTML = output;
}
Since modal and element are IDs, you should correct your selectors to use them as ones:
$('#' + modal).addClass('reveal-modal');
$('#' + element).addClass('samples');
Side note. Once you have found the DOM element with jQuery, there is no need to perform the second search with getElementById:
var modal_loc = $('#' + modal);
modal_loc.addClass('reveal-modal');
modal_loc.html(modal_output);
if modal is an ID string, you need to do:
$('#'+modal).addClass('reveal-modal');
Try changing:
$(element).addClass('samples');
to
$('#' + element).addClass('samples');

Adding and removing elements in Javascript?

I'm trying to make a generator for a mod menu in Call of Duty. I want people to be able to add a menu or delete one. I'm trying to id the menus sequentially so that I can use the text field values correctly. I made it so that if they delete a menu it changes the ids of all the other menus to one lower and same for the button id, but I don't know how to change the onlick event to remove the right element.
Better yet, if there's a better way to do this, I would love to know it.
<script type="text/javascript">
y = 1
function test2()
{
document.getElementById("test2").innerHTML += "<div id=\"child" + y + "\"><input type=\"text\" value=\"menu name\" \><input id=\"button" + y + "\" type=\"button\" value=\"remove?\" onclick=\"test3(" + y + ")\" /></div>";
y++;
alert(y);
}
function test3(x)
{
document.getElementById("test2").removeChild(document.getElementById("child" + x));
for(var t = x+1;t < y;t++)
{
alert("t is " + t + ". And y is " + y);
document.getElementById("button" + t).setAttribute("onclick" , "test3(t-1)");
document.getElementById("button" + t).id = "button" + (t-1);
document.getElementById("child" + t).id = "child" + (t-1);
}
y--;
}
</script>
<input value="testing" type="button" onclick="test2()" />
<div id="test2" class="cfgcode"></div>
I wouldn't worry about re-indexing all of the elements after you add or remove one, that seems a waste. It would be better to simply write a more generic function, rather than one with the element id hard coded into it.
For example, your first function could be written as so:
function genericFunction(el)
{
var html = ''; // create any new html here
el.innerHTML = html;
}
You can then add onclick handlers such as:
myDiv.onclick = function() { genericFunction(this) };
I would also agree with all the commenters above, use jQuery, it makes any code which interacts with the DOM much much simpler.

Categories

Resources