Javascript not firing when changing HTMLDropDownListFor value - javascript

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.

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 + ", ")

Update some fields on change and on load

We have the following script which runs on a change to a drop-down - updates the price based on the currency code chosen. This basically gets the value of the drop-down and updates the priceamm and preicecurr fields within the text on the page.
<script>
function run() {
var f = document.getElementById("dropPrice");
priceamm.innerHTML = f.options[f.selectedIndex].value;
var e = document.getElementById("dropPrice");
pricecurr.innerHTML = e.options[e.selectedIndex].text;
}
HTML
<select id="dropPrice" onchange="run()" class="fa-select">
<option value = "a">aaa</option>
<option value = "b">bbb</option>
Question
Now, we would also like to load the drop-down to one of the options (selected) when loading the page (onload). We are able to populate the variables in the text but not the drop-down to show option bbb. In php this is quite easy but we are a bit lost with javascript. We tried something on these lines onload but does not work:
document.getElementById("dropPrice").value = "<?php echo $geo_price ;?>";
With jQuery this is probably easier but once again no luck:
window.onload = function() {
jQuery(document).ready(function($){
document.getElementById('dropPrice').find('option[value=<?php echo $geo_price ;?>]').attr('selected','selected');
});
}
Any help is appreciated. Thanks
The jQuery selector part is incorrect. You are mixing plain JS with jQuery. When you call document.getElementById('dropPrice') a regular DOM element is returned, but then you call find which is a jQuery method to be used on a jQuery element. So, you either need to wrap the first part to return a jQuery element like so:
$(document.getElementById('dropPrice'))
.find('option[value="b"]').attr('selected', true);
Or, select it via jQuery in the first place like:
$('#dropPrice [value="b"]');
However, your first example:
document.getElementById("dropPrice").value = "b";
should work. That makes me wonder if the value that is being echoed by PHP is correct and/or if there are other JS errors being thrown that would cause that code not to run.

How to get ids from divs that were dragged into a drop zone on button click javascript

I'm trying to find a way to get the ids from dragged divs after they are in the drop zone.
All the drag components have an id from drag1 - drag8 and the drop zone is div drop zone. Because there are no divs in the drop zone when the page loads I want to gather the ids on a save button for now with a text box entry and drop down menu select.
I have tried the code below:
$(document).ready(function() {
$("#dropzone div").click(function() {
var index = $("#dropzone div").index(this);
$("#dropzone_drag").html("Index " + drag + " was clicked");
});
});
And I use jQuery for the text box, which works nicely:
$(document).ready(function() {
$('#save').click(function() {
alert($('#name').val());
});
});
How do I find the ids from dragged divs after they are in the drop zone?
After playing around i came up with the following:
var ids = {};
$("#dropzone>div").each(function(i){
ids[i] = $(this).prop('id');
});
which at the moment says undefined, but i did manage to put it on the save button so it no longer pops up when i open the page.
Any suggests please?
In my comprehension .index(this) returns the index of the element relative to the list "#dropzone div"., which may or may not contain the elements in the order you want. But if all your elements have a common class, say ".foo_bar" it probably would be easier to know the id given an clicked element.
Otherwise, as you're using this on the function, if this is one of your "drags" it is probably easier to pick the id from this than to try the indexes.
Try doing it like that and maybe it'll word better.
ids = {};
$("#dropzone>div").each(function(){
ids[$(this).prop('id')] = $(this).prop('id').replace(/[^0-9]/g, '');
});
the code .replace() means that we are removing characters (in this case anything that isn't a number) from the string so we end up with it's true number. Instead of it's place in the DOM.
If i didn't comprehend well your problem, correct my comprehension errors and i will edit the answer. And an html of the zones would be nice ;)
The following code worked for me:
<script>
var div = document.getElementById('dropzone')
</script>
and on the button i added:
alert( div.innerHTML )
The result gave me all of the div information from it's html page so i could select the information i wanted to push to the database.
Thank you all for you input and advice.
Matthew

jQuery selector can't find added elements in DOM

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.

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