jquery remove not removing - javascript

so I've got this form:
<form id="imageinputpopup" class=suggestionsubmit style="display: none">
<span>Add a thing!</span><br/>
<label>url: </label><input name="imageurl" type="url"><br/>
<label>file: </label><input name="imagefile" type="file"><br/>
<input type='hidden' name='schoolid' class="schoolid">
<input type="submit" value="Submit">
</form>
and this click handler:
$(".allow-submission").live('click', function(){
if($(this).attr('inputtype')=="colorpicker"){
....
} else if($(this).attr('inputtype')=="image"){
remove_hidden("#imageinputpopup");
add_fieldname($(this), $("#imageinputpopup"));
$("#imageinputpopup").dialog();
} ....
});
remove_hidden looks like:
function remove_hidden(element){
alert($(element).children('.fieldname').length);
$(element+'.fieldname').remove();
alert($(element).children('.fieldname').length);
}
and add_fieldname looks like:
function add_fieldname(element, addto){
var elementname = document.createElement('input');
elementname.type = 'hidden';
elementname.name = 'fieldname';
elementname.value = element.attr('fieldname').replace(' ', '_');
$(elementname).addClass('fieldname');
addto.append(elementname);
}
as I expect, with each click, a tag like this is added:
<input type="hidden" name="fieldname" value="mascot_image" class="fieldname">
but remove_hidden isn't removing!
I know the selector is right because the alert is exactly the number of these input tags, but they're just not getting removed. Why? I also tried $(element+).remove('.fieldname'); and that didn't work either.

In this line of remove_hidden
//Select the element with the id of element AND has the class of fieldname
$(element+'.fieldname').remove();
Try putting a space before the . like so:
//Select the children of element which have a class of fieldname
$(element+' .fieldname').remove();
EDIT: Added comments above to clear things up a bit

If I get this source right, on one hand you don't have an ID on the input you get when you add a fieldname with the add_fieldname function. You might want to set that for ease of use.
On the other hand, in the remove_hidden function you alert out the element .fieldname, but trying to remove the element.fieldname (notice the missing space in front of the class name), so I presume you need this in the remove_hidden function:
$(element+' .fieldname').remove();
I hope it helps.

try replacing
$(element+'.fieldname').remove();
with
$(element+' .fieldname').remove();

It's because .remove([selector]) "filters the set of matched elements" to decide what to remove.
Their documentation threw me off at first. What you are trying to remove already needs to be in the collection (no selector in the remove method would remove the entire collection).
Ex: Remove input.fieldname:
$(element).find('.fieldname').remove('.fieldname');
or (for the larger case collection case):
$(element).find('input').remove('.fieldname');
Ex: Do NOT remove input.fieldname:
$(element).find('input').remove('.notfieldname');

Related

Get the value of an <input type="text"> that was created dynamically inside a modal

i would like to get the value of an <input type="text"> that was created dynamically inside a modal and put it into variable "newcomment".
This is how i make the input:
var newcomment;
var p = $("<p>");
p.append("Some text");
p.append("</p>");
p.append("<input type='text'id='comment_text' value='Comment'"+"onblur=newcomment=$('#comment_text').val()"+" onfocus=if(this.value==this.defaultValue)this.value=''>"+"</input>");
$("div.modal-body").append(p);
The problem is when i write something like "ok" inside the textbox in the modal, and after i focusout from the textbox: newcomment seems not update to "ok" and still have the default "Comment" value.
1st: You need to use newcomment=this.value instead of newcomment=$('#comment_text').val()
2nd: No need to add + signs in your input html code while you not trying to concatenate string by putting variables to it
var newcomment;
var p = $("<p>");
p.append("Some text");
p.append("</p>");
p.append("<input type='text' id='comment_text' value='Comment' onblur='newcomment=this.value; alert(newcomment);' onfocus=if(this.value==this.defaultValue)this.value='' />");
$("body").append(p);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Not really the answer here, but might help you get at the root of the problem.
JS:
var newComment, defaultValue;
function doOnBlur(){
newComment = $('#comment_text').val()
}
function doOnFocus(){
if($('#comment_text').val() == defaultValue){
$('#comment_text').val('')
}
}
HTML:
<input type='text' id='comment_text' placeholder='Comment' onblur='doOnBlur()' onfocus='doOnFocus()' />
<!-- inputs dont have a close tag, also should use placeholder for temporary text -->
from here, you can set breakpoints in the debugger and see where your code is going wrong. You can also modify the functions much more easily rather than writing the executing code in the HTML

JQuery: Select all ids ending with specific name and change its siblings input button

I'm trying to indicate that a text can't be sent just yet, showing a grey input submit button with the class btn-primary. Instead btn-default is a coloured input button.
However there are many textareas on one single site as my JQuery code should be used for both posting a new status and to comment several status entries (like in Facebook).
That's why posting a new status has an unique id called status_textarea and the comment textarea has an id like comment_textarea39 for example. So there is always a number at the end of comment textareas. That's what my first problem is with my code:
$('[id$=_textarea]').on('click contextmenu keyup blur', function(e) {
var text = $(this).val();
var button = $(this).parent().hasClass('btn-primary');
button.val(123); // Test to find the input button
if (text.length < 1) $(button).removeClass('btn-default').addClass('btn-primary');
else $(button).removeClass('btn-primary').addClass('btn-default');
});
I can select my status textarea with this, but not my comment textarea(s) as these have an id at the end like I mentioned (example: comment_textarea39). So I need something like a wildcard selection that only searches for: id ending with _textarea and ignores what the id is named after that.
Then I also want to select the next input (nearest after "this" textaera) that has the class btn-primary to switch it to btn-default.
EDIT
HTML Example:
Status Post Textarea:
<form id="statusForm">
<input type="hidden" name="privacy" value="0" autocomplete="false">
<textarea id="status_textarea" name="text" style="min-height:55px"></textarea>
<input id="status" data-case="status" data-form="#statusForm" type="submit" class="modal-send mt15 mb15 btn btn-primary" value="Senden" autocomplete="false">
</form>
Comment Textarea:
<form id="commentForm82">
<textarea id="comment_textarea82" name="text" class="comment mb15" placeholder="Hier kommentieren..."></textarea>
<input type="hidden" name="log_id" value="82" autocomplete="false">
<input id="comment" data-case="comment" data-form="#commentForm82" data-hide="1" data-hide-success="1" type="submit" class="modal-send pull-right btn btn-default" value="Senden">
</form>
Use the attribute contains selector instead of ends with selector as you have a dynamic part at the end of the id attribute
$('[id*=_textarea]')
Another better choice will be is to use a class selector, ie assign a common class like textarea to all the elements that needs to be selected then use
$('.textarea')
I would recommend you use a common class to bind events, i.e. add a class such as yourClass then you can use class selector
$(".yourClass").on('click contextmenu keyup blur', function(e) {
});
However, use Attribute Contains Selector [name*=”value”] to bind events and .find() within the event handler to identify input instead of hasClass()
$('[id*=_textarea]').on('click contextmenu keyup blur', function(e) {
var text = $(this).val();
//Important: Notice Here
//Use find as hasClass returns you true/false not element
var button = $(this).parent().find('btn-primary');
if (text.length < 1) {
$(button).removeClass('btn-default').addClass('btn-primary');
} else {
$(button).removeClass('btn-primary').addClass('btn-default')
};
});
for those more old-fashioned, just search each textarea for an id containing 'textarea', return it if it matches the pattern in MAP:
var theseTextAreas = $('textarea').map(function(){
if ($(this).attr('id').indexOf('textarea') > -1)
{
return $(this);
}
});

Set the default value of an input text

my requirement is to save the entire "html" inside a div, but when i load an "html" with text fields to a div and then editing the value of the text box, the newly set value doesn't reflect in the core "html". I tried to inspect the value with fire bug and it remains the same or no value at all.With "jquery" i tried to set attribute but no attribute name value is created. how can i set the value of text fields and then get that "html" with the newly set value.
here is my html
<div class="sub_input_box">
<input type="text" / class="boreder_line">
<input type="text" id="txt" value=""/>
<input type="hidden" id="hid" />
<div class="clear"></div>
</div>
and the jquery i used to set attribute
$("#txt").attr("value", "some value");
Chances are you're calling your jQuery code before the HTML input part. You can either place the jQuery stuff below it, or if you don't want to, you can do something like this:
$(document).ready(function(){
$("#txt").attr("value", "some value");
});
That will only run when the page is fully loaded.
However, it's unclear if you're using AJAX to load those inputs into your DOM. If so, you need to call $("#txt").attr("value", "some value"); in the onSuccess callback function which is fired after the AJAX successfully responds.
You can try something like this:-
<input name="example" type="text" id="example"
size="50" value="MyDefaultText" onfocus="if(this.value=='MyDefaultText')this.value=''"
onblur="if(this.value=='')this.value='MyDefaultText'" />
Have you tried:
$("#txt").val("Hello World!");
For setting the text value, and,
var my_string = $("#txt").val();
For getting the text value.
Let me know if it works.
Excellent question. You would think clone would do this on its own, alas, it doesn't.
Here is a sample than you can hopefully adapt to do what you need
HTML
<div id=divToCopy>
<input name=i1 value=foo><br>
<input name=i2 value=bar>
</div>
<input type=button onclick=copyDiv(); value='Copy the div'>
<div id=newDiv>
the copy will go here
</div>
JavaScript
function copyDiv() {
$('#newDiv').html($('#divToCopy').clone());
$('#divToCopy :input').each(function() {
var child=0;
for (var i = 0; i < this.attributes.length; i++) {
var attrib = this.attributes[i];
var prop=$(this).prop(attrib.name);
$($('#newDiv').find(' :input')[child]).prop(attrib.name,prop);
child++;
}
});
}
But it does work: http://jsbin.com/eXEROtU/1/edit
var html = '<input type="text" id="txt" value=""/>';
$(document).ready(function() {
$("#load").click(function() {
$("#sub_input_box").html(html);
});
$("#inspect").click(function() {
alert($("#txt").val());
});
});
$(document).on('focusout','input[type="text"]',function(a){
console.log(a.target.value);
a.target.setAttribute("value",a.target.value);
});
this is the solution i found, i had to set the value attribute explicitly on loose focus from the text field

JQuery - Append to text area that has been modified with Jquery

I am trying to append the value of a div or a input box to my text area. I have this working no problem but if i clear the contents of the text area first with a Jquery action it doesnt allow me to use my append features.
E.g.
<script type="text/javascript">
$(document).ready(function() {
$("#Column1").click(function () {
$("#sql").append($("#Column1").val())
})
$("#Column2").click(function () {
$("#sql").append($("#Column2").html())
})
$("#reset_sql").click(function () {
$("#sql").val('SELECT ')
})
</script>
<div> <input type="checkbox" name="column1" id="column1" value="`Column1`"> column1 </div>
<div id="Column2"> Column2 </div>
<textarea rows="10" cols="80" name="sql" id="sql"><? echo $sql ;?></textarea>
<input type="submit" value="submit" />
<input type="button" value="reset sql" id="reset_sql" />
The input and div lines above are just generic examples but relate exactly to what i'm trying to do.
I dont understand that when i clear the text area with javascript that my appends wont work. I get no JS errors in firefox error console.
thank you
You have several issues with your code: you haven't closed your document.ready callback, you are using the incorrect case when refering to your ID's, and you're using some of the jQuery methods incorrectly. For example, append() appends HTML to an element, whereas you want to update the value.
Your logic isn't quite correct either, since columns won't be removed when you uncheck a checkbox, and the columns won't be comma delimited (it looks like you are building a SQL string here).
I believe something like this is what you're looking for:
$(document).ready(function() {
var $sql = $('#sql');
var initialValue = $sql.val();
$("#column1, #column2").on('change', function () {
var cols = [];
var checked = $('input[type="checkbox"]').filter(':checked').each(function() {
cols.push($(this).val());
});
$sql.val(initialValue + ' ' + cols.join(', '));
})
$("#reset_sql").on('click', function () {
$sql.val(initialValue)
})
});
Working Demo
Your checkbox has an id of 'column1', but your event handler is $("#Column1").click(function () {.
Case matters! Either change the id to 'Column1' or the event handler to look for $('#column1').
Demo

javascript in html

i am using javascript to change the text of div tag on run time.
how can this be done..
my div tag is as:
<div id="topdiv" style="color:Blue" onmouseover="button1();">
<input type="button" id="btndiv" onclick="edit1();"/>
Div Tag
</div>
i wnt the user to input text on runtime in div and that should be displayed in div.
can someone help me..
It should be innerHTML. innerHTM is not a javascript function.
You don't get a magic variable just by having an element with an id. var something = document.getElementById('some-id')
The property is called innerHTML not innerHTM
innerHTML is a string variable not an function. Assign a value to it with =, don't try to call it with ()
function edit1() {
alert('you are in edit1');
document.getElementById('topdiv').innerHTML = 'hello';
}
and with proper error handling:
function edit1() {
alert('you are in edit1');
var topDiv = document.getElementById('topdiv');
if (topDiv != null) {
topDiv.innerHTML = 'hello';
} else {
alert('topdiv is nowhere to be found in this DOM');
}
}
Try document.getElementById('topdiv').innerHTML = "Hello"
To get the div you should use document.getElementById('topdiv'). There is indeed a WebKit feature, that elements with an ID are automatically expanded as global variables, but it's highly questionable, that this becomes mainstream.
Then, innerHTM should read innerHTML, and you assign directly:
foo.innerHTML = "hi there"
you should use
document.getElementById('topdiv').innerHTML = 'hello';
You should use references instead of ID's, using this.
In that case this means the node that triggers the event.
<div style="color:Blue" onmouseover="button1(this);">
<input type="button" onclick="edit1(this);"/>
Div Tag
</div>
function button1(divRef){
//divRef is the reference to the DIV
}
function edit1(inputRef){
//inputRef is the reference of the INPUT
//inputRef.parentNode is the reference to the DIV
}
function edit1() {
alert('you are in edit1');
document.getElementById('topdiv').innerHTML = 'hello';
}
This should work by specifying the id
In standard JavaScript usage you'd do as per #DarinDimitrov 's answer.
document.getElementById("topdiv").innerHTML = ('hello');
Once you're happy with JavaScript I would suggest you look at the JQuery libraries - the powerful syntax will let you write short, neat code like this:
$("#topdiv").html('hello');
Your file
<div id="topdiv" style="color:Blue" onmouseover="button1();"> Div Tag</div>
<form><input type="button" id="btndiv" value="Edit" onClick="window.open('t2.html','popuppage','width=850,toolbar=1,resizable=1,scrollbars=yes,height=700,top=100,left=100');" value="Open popup"/></form>
t2.html file
function sendValue (s){var selvalue = s.value;window.opener.document.getElementById('topdiv').innerHTML = selvalue;window.close();}
<form name="selectform"><input name="details" value=""><input type=button value="Copy input to parent opener" onClick="sendValue(this.form.details);"></form>
Got Idea from this source enter link description here

Categories

Resources