Change href value with JS from select box - javascript

I have this select box that gets its data from my DB.
What I want to do is add Edit and Delete buttons next to my select box that will do the respective actions on the current selected option.
So I added two buttons that direct to php scripts that do all this work.
My problem is with JavaScript where I need to update the elements of the buttons.
However my JS function doesn't work.
It appears that it isn't even fired.
http://jsfiddle.net/y5g42/33/
HTML:
<select name='selectHotel' onChange='updateButtons(this.options[this.selectedIndex].text)'>
<option value="volvo.php">Volvo</option>
<option value="saab.php">Saab</option>
<option value="mercedes.php">Mercedes</option>
<option value="audi.php">Audi</option>
</select>
<a href='' id='editButton'><button>Edit</button></a>
<a href='' id='deleteButton'><button>Delete</button></a>
JavaScript:
function updateButtons(var) {
element = document.getElementById('editButton');
element.href = var;
}​

You can't use var as variable name - var is javascripts reserved word.

You have several problems with your logic and the fiddle itself.
Best way without using JavaScript library is to attach the onchange handler in the onload of the window and handle everything there:
window.onload = function() {
var oDDL = document.getElementById("selectHotel");
oDDL.onchange = function updateButtons() {
var oLink = document.getElementById('editButton');
oLink.href = oDDL.value;
};
oDDL.onchange();
};
To have it work, add id="selectHotel" to the <select> element and remove the inline onchange from it.
Updated fiddle.
In your initial fiddle you didn't choose proper framework properties.
Note that I am calling the onchange manually one time to reflect the selected value, otherwise clicking the button before selecting other value won't work.

jsFiddle's onLoad option wraps your code in a callback function.
Therefore, your function definition isn't visible outside the code.
You need to select No Wrap instead.

You just passed value rather than text on onchange function
onChange='updateButtons(this.options[this.selectedIndex].value)'
You can try something like this :
window.updateButtons = function(value) {
element = document.getElementById('editButton');
var url = window.location.href;
element.href = url + value;
console.log(element.href);
}
See Demo : http://jsfiddle.net/y5g42/46/

Related

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 document property value in html script

Is there a way to get document property values into html script in text area.
for example:
I have a drop down which have values like "google","yahoo","Facebook"
and my html script may be like
< SpotfireControl id="a23e53a498af447294614ec708f50ede" /> A href="http://www.Document propety value.com/">.
So if you select google in drop down ,the above html script will change to
< SpotfireControl id="a23e53a498af447294614ec708f50ede" /> A href="http://www.google.com/">
I want to see this dropdown and link in one text area.
much appreciated
If your tag is as follows:
<a id="mylink" href="">
Then you can set the href like so:
document.getElementById("mylink").href = "https://google.com";
If your select has an id="myselect", you can get the value like so:
document.getElementById("myselect").value
Now you can set your link:
var site = document.getElementById("myselect").value;
document.getElementById("mylink").href = "https://"+site+".com";
Now, you want this to happen when you change the drop-down (select) option, so you'll need to add an event listener for when it changes.
document.getElementById("myselect").addEventListener("change",
function() {
var site = document.getElementById("myselect").value;
document.getElementById("mylink").href = "https://"+site+".com";
}
}
Do note that your event listener can only be added after the selector and the link have loaded (so the code needs to be afterwards). If you've never used JavaScript before, you should note that you need <script type="text/javascript"> and </script> tags to enclose it.

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.

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);
});
});

Weird behaviour with change event in HTML

I have a struts tag like this
<s:select label="Select Item" name="select3ph3meter1" id="select3ph3meter1"
headerKey="0" headerValue="-- Please Select --" list="meterHeaderList"
required="true" onchange="show_3ph3meter1(this.value)" />
The problem is it is not calling the above function on change event. It works when I change the code to this:
... onchange="alert('calling')"
I can't understand what's happening here.
Here is the JavaScript function:
function show_3ph3meter1(select3ph3meter1) {
$("#3ph3meter1").load("meterFiller3p31.action",{select3ph3meter1:select3ph3meter1});
}
function show_depotReceipts(selectrecitem) {
$("#recQuantity").load("depotRecQ.action",{selectrecitem:selectrecitem});
$("#recRange").load("depotRecRange.action",{selectrecitem:selectrecitem});
}
The adjacent function is working perfectly so I assume there is no JavaScript error.
Also, when I put in another function (for instance the adjacent function name in onchange), it is also working. The problem may be with this particular function name show_3ph3meter1().
Hi if you have some other java script written over there contains errors , this code wont work.
So better have like this
<select class="style" onchange="//do something like this
//var e = document.getElementById('selectelement'); //if (e) e.value=100;" />
please check in IE browsers to get the java script errors. write entire code in that change event
First check your calling function name
if this is correct then just write
onchange="javascript : show_3ph3meter1(this)"
and get value on the function
3 else try the access value in function with selector
var elem = document.getElementById("short_code"),
selectedNode = elem.options[elem.selectedIndex];
var valu = selectedNode.value;

Categories

Resources