jQuery selector can't find added elements in DOM - javascript

I know that the solution is the jQuery.on-function but it don't work as I expect it would do.
Following problem:
I pull via Websocket(JSON) data and build my page up inside the document ready function (for connection reasons).
That means I add several input fields via the jQuery.append()-function and try to access the select-input when the SET button is pressed. Accessing the select input fails.
I have selected the body as parent element, every other form field should be in it.
For demo reasons I removed the Websocket-Functions. I have hardcoded the form as it would be in real. The debug-messages are displayed in the firebug-console.
Here is the fiddle: http://jsfiddle.net/gLauohjd/
This is the way I am accessing the select input
$("body").on('click', ':button', function () {
console.log( $( this ).text() ); //Value of the pressed button
var ip = $(this).attr('ip');
var selectvalue = "#" + "modeselect" + ip;
console.log(selectvalue); //Print the selector to verify it is ok
console.log($(selectvalue).val()); //fails ->not found in DOM
Any help on that is very appreciated!

To select a tag with jQuery, use just the tag name.
$("body").on('click', 'button', function () { .. } // any button clicked on body
As for actually retrieving the values, you won't be able to do so unless you escape the dots.
$("#modeselect127\\.0\\.0\\.1").val();
You could use something like:
var selectvalue = "#" + "modeselect" + ip.replace(/\./g, "\\\\.");
Hope this helps.

Related

Can't figure out how to grab value of button click event and paste it into a text input field

I have been building this app that helps people play Yahtzee without dice. It's essentially a random number generator visually displayed in the DOM.
I'm trying to add in some extra functionality by letting players click on the generated numbers which are stored in the DOM in button elements. And by clicking on them it stores that number into the text input field below that.
I tried multiple different things to paste the value into the input field but nothing seems to work or throw any errors. Logging the value to the console on click works just fine.
TLDR explanation in video(sorry for shitty audio): https://www.loom.com/share/449c370364b448349e20a06085dae5d5
Github link: https://github.com/Roaldkamman/Portfolio_YahtzeeDice
most important code piece I'm trying to fix:
$(".dice-button").on("click", ".btn_1", function() {
$(".myInput").value = this.textContent + ", ";
});
How logging to the console works:
$(".dice-button").on("click", ".btn_2", function() {
console.log(this.textContent);
});
Thanks in advance for any help! :)
.value is a property on a HTML input element, not on the jQuery object. So, you should either use jQuery's .val() to set the value, or retrieve the HTML element from the object:
$(".myInput").val(this.textContent + ", ");
...or:
$(".myInput")[0].value = this.textContent + ", ";
In jQuery use method val() in input element
$(".myInput").val(this.textContent + ", ")

javascript for all textarea

I want apply my JS on all my Textarea
$_PAGE->addJSOnLoad("
$('#textarea').keyup(function() {
var nombreCaractere = $(this).val().length;
var msg = nombreCaractere + ' caractére(s)';
$('#compteur').text(msg);
'<span id=compteur>' 0 caractére(s)'</span>';
});
");
This code is in constructor of my class textarea I wnat call him 1 times for all textarea
You should change the jquery selector from $('#textarea') to $('textarea') so as to target all textarea in the document.
Also you may want to use $('.compteur') in place of $('#compteur') so that your can have multiple counters, one for each textarea. Do not forget to update your html correspondingly
Edit: Please use $(this).find('.compteur') in place of $('.compteur') so that only the counter within the current textarea is affected
$('#textarea')
selects a HTML element with the ID "textarea". So this will be at max one textarea-element. The selector for all textareas would be just
$('textarea')
javscript event handlers can take a parameter (Event), so
$('textarea').keyup(function() {
var nombreCaractere = $(this).val().length;
var msg = nombreCaractere + ' caractére(s)';
// code for display, todo!
}
would put the event handler on every textarea (<textarea>) on your page. However, the display for the character count is a bit more difficult, unless it's one fixed element that scrolls along.
but let's say, your textareas all have an attribute data-charcount="[id]" that has the id of a div or something, that will display the character count.
Then you could replace
// code for display, todo!
with
$("#"+this.dataset.charcount).text(msg); // <- assuming this works
and your example textarea should look like this:
<textarea data-charcount="compteur"></textarea>
<span id="compteur"></span>
please note: every id should only appear once!
edit replace event.target with this, and fixed small error with string concat

Javascript not firing when changing HTMLDropDownListFor value

I have this dropdown list.
#Html.DropDownListFor(m => m.Puppies, Model.Puppy.PuppyList, new { #class = "dashboard-control", placeholder = "Select Puppy" })
Markup:
<select class="dashboard-control" data-val="true" id="Puppies" name="Puppies" placeholder="Select Puppy"><option value="2">Lab</option>
Poodle
The name and id of this dropdown is Puppies, verified in Inspector.
I have this javascript in my View:
<script type="text/javascript">
$(document).ready(function() {
$("#Puppies").on("change", function() {
var selected = $(this).val();
$("#description").html("You selected: " + selected);
})
});
</script>
When I place a break in the Chrome Sources window on the function, it only stops there on page load. I don't see any obvious problems. According to the documentation I read for .on, it should fire when the value is changed. I even tabbed out of the combo to see if that was when it would fire. What am I missing?
Not seeing where there's anything wrong with your code. this is essentially the same thing, and I've tested both ways.
edit
Now that you've made clearer the id you're using, you should escape the period in the jquery selector so that it doesn't mistake it for a class. code tested, works.
$(function() {
$('#Animals\\.Puppies').on("change", function() {
var selected = $(this).children(':selected').text();
$("#description").html("You selected: " + selected);
}).change();
});
Try:
$("body").on("change", "#Puppies", function()
{
var selected = $(this).find(":selected").val();
});
Ok, this is working now. In my attempt to obfuscate the model and id of the drop down, I manually typed the id #Animals.Puppies' in the demo code. Well, apparently HTML helpers, such as the one I was using #Html.DropDownListFor, change periods to underscores automatically in the id. Since I was placing a period in the function when referencing the ID, naturally it never fired on change of the drop down. There is a discussion about this and the code that does this, in this question Preventing ASP.NET MVC from Replacing period with underscore in Html Helper IDs
When I referenced the id of the dropdown correctly with the underscore, not a period, the script worked.

How to replace a letter with another letter in a textbox

Say I want to target a specific letter in a textbox region and replace it with another letter using either jquery or javascript, how would I do that and still be able to target another letter afterwards, and again, and again etc.? The letter to change and what it will be changed to will be inputed from either a textbox or a dropdown (whichever is easier)
P.S I tried jQuery's replace function and it didn't work (I probably didn't use it correctly though :)
$( "button" ).click( function() {
$( "Changed" ).replaceWith( $( "New" ) );
});
$("button").click(function() {
var old = $("#Changed").val();
var replacement = $("#New").val();
var regexp = new RegExp(old, 'g');
$("#Input").val(function(i, current) {
return current.replace(regexp, replacement);
});
});
You need to use # before IDs to select them.
You need to get the values of the inputs using .val().
jQuery's .replaceWith is for replacing entire DOM elements, not changing the value of an input.
You use .val() to change the value of the input. When the argument is a function, the function gets called with the current value as a parameter, and the return value is put in its place.
The Javascript method .replace() is used to perform replacements in strings. To do multiple replacements, you need to use a RegExp with the g flag.
DEMO
Please Check following code if it helps : http://jsfiddle.net/La2y734g/2/
HTML as follows
<textarea id="Input" cols="50" rows="5">This textbox has been given a name of "myTextBox". This can be used by any script that process the contents of this textbox (once it's been submitted to the server).</textarea>
<br>Replace
<input type="text" id="replace">with
<input type="text" id="with">
<button>Detect Single Letters And Replace</button>
Javascript as follows
$("button").on("click", function () {
//$( "#Input" ).replaceWith( $( "Change" ) );
var toReplace = $('#replace').val();
var withText = $('#with').val();
var newText = $("#Input").val().replace(toReplace, withText );
$("#Input").val(newText);
});

Dynamically created textarea with no .val()

I'm trying to allow users to edit the text of a paragraph in a website. I take a paragraph and replace the <p> tags with <textarea> tags using the .replaceWith() function. When I try to take the value of the textarea, it returns blank. Here's a JSfiddle.
HTML:
<p><a class="edit">Edit</a>I'm going to change this into a textarea field and retrieve the value.</p>
JS:
$(document).ready(function() {
$('.edit').hide();
var object = $('p');
object.on("mouseenter", function() {
$('.edit').show();
object.on('click','.edit',function(){
var oldText = object.text();
oldText = oldText.substr(4); // Exclude the word 'Edit'
object.replaceWith($("<textarea>").val(oldText).css("width",object.css('width')).css('height',object.css('height')));
var value = object.val();
alert("Value: "+value);
});
});
});
I'm a programming beginner, so if you have style or implementation tips, feel free to share. This is just my gut reaction to solving the problem; there may be a simpler way to accomplish the same thing.
EDIT: I should also mention that in my website, each paragraph comes from a database table that I'm displaying using an AJAX function. When the user is done editing, he can click a button, and the website will take the new value of the textarea field and UPDATE *table* SET *text*=newText WHERE *text* LIKE oldText;
Try just using contenteditable='true' instead of changing to a textarea. It will make the <p> editable.
Like this:
<p contenteditable='true'><a class="edit">Edit</a>
I'm going to change this into a textarea field and retrieve the value.</p>
If you want to make your text area editable when someone clicks 'Edit', you can create a function that sets the contenteditable attribute to true and then gives focus to the <p> element.
Your code is not trying to get the value of the <textarea>. Your call:
object.replaceWith( ... )
does not change the value of the variable "object" — it's still the jQuery object for the <p> tag, but after that it's out of the DOM. <p> tags don't have a "value" property.
It's almost always a bad idea to set up event handlers inside another event handler (well, an event handler for interaction events anyway). Event handlers accumulate, so each "mouseenter" event will add another "click" handler.
ckersch is right about an easier method being to use contenteditable, but if you're looking to a solution for your specific problem, change your selector from this:
var value = object.val();
To this:
var value = $("textarea").val();
Full code:
$(document).ready(function() {
$('.edit').hide();
var object = $('p');
object.on("mouseenter", function() {
$('.edit').show();
object.on('click','.edit',function(){
var oldText = object.text();
oldText = oldText.substr(4); // Exclude the word 'Edit'
object.replaceWith($("<textarea>").val(oldText).css("width",object.css('width')).css('height',object.css('height')));
var value = $("textarea").val();
alert("Value: "+value);
});
});
});
Fiddle
There are many ways you could make it more robust, including adding a class or id to your textarea, and then using it to be selected, such as this way:
object.replaceWith($("<textarea class='selectMe'>").val(oldText).css("width",object.css('width')).css('height',object.css('height')));
var value = $(".selectMe").val();
You are using the method replaceWith() wrong. The argument must be a string or a function that returns a string, not a jquery selector. Also, you should place the onclick event outside of the mouseenter event (this is valid for any event, never nest them)
$(document).ready(function() {
function makeTextarea(e) {
e.preventDefault();
var edit = $(e.currentTarget);
var parent = edit.parent();
edit.remove();
parent.replaceWith('<textarea>' + parent.text() + '</textarea>');
}
$('.edit').on('click', makeTextarea);
});
Fiddle: http://jsfiddle.net/U57v2/4/
"When the document is ready listen for clicks on .edit class. When clicked store a reference to the parent element (<p>) and then remove the edit element. Finally replace the parent element (<p>) with a textarea with the contents of the <p> element."
ckersh is absolutely right about the contenteditable, but if you're looking for a specific answer to your code, there are a few things you could improve.
There are a couple of issues with your code. First, you're rebinding the on('click') handler every time you mouse over the paragraph, so if you mouse over 5 times, you're executing the anonymous function 5 times. You only need to bind the on routine once. Second, the variable object never changes, so when you replace it with a textarea, you need a new selector to get the value.
I've updated your fiddle with the enhancements I've mentioned above. I also added a mouseleave event, because I figure you want to hide the "Edit" button when you leave the paragraph. The updated javascript can be seen below:
$(document).ready(function () {
$('.edit').hide();
var object = $('p');
object.on("mouseenter", function () {
$('.edit').show();
}).on("mouseleave", function () {
$('.edit').hide();
}).on("click", '.edit', function () {
var oldText = object.text();
oldText = oldText.substr(4); // Exclude the word 'Edit'
object.replaceWith($("<textarea>").val(oldText).css("width", object.css('width')).css('height', object.css('height')));
var value = $("textarea").val();
alert("Value: " + value);
});
});

Categories

Resources