Domanda

I'm new to JavaScript and I need some help with a simple problem I'm having:

I have one empty input field, and two links (anchors) with differing values for the title attribute.

I'd like to write a small piece of JavaScript that changes the value of the input element to the title of whichever link the user clicks.

For example:

First link = Prague
Second link = Budapest

When I click "Budapest" I'd like the value of the input element to change to "Budapest"

If needed I can supply a basic jsFiddle but hopefully I've made myself clear enough.

È stato utile?

Soluzione

If the project is really this small then it's probably easier to just attach some onclick handlers to your anchors, and then define a very basic function to update the input element.

HTML

<a href="#" title="Prague" onclick="updateValue(this.title, event);">Prague</a>
<a href="#" title="Budapest" onclick="updateValue(this.title, event);">Budapest</a>
<input type="text" id="country" name="country" value="" />

JavaScript

function updateValue(val, event) {
    document.getElementById("country").value = val;
    event.preventDefault();
}

Example: http://jsfiddle.net/zUVA5/

If you have a large amount of anchors then adding individual onclick handlers by hand would be quite a pain, to avoid this you can simply wrap your content in a containing element and then apply click event handlers to all nested anchors programmatically:

Example: http://jsfiddle.net/FUvYC/

Altri suggerimenti

The process would be to find all of the anchors, then attach a click handler which sets the input value to the clicked anchor's title attribute. The example below finds all anchors on the page, but you might prefer to add a class and use document.querySelectorAll() (which is not fully supported by old IE).

Demo

HTML

<input type="text" id="myinput" value="" />
<a href="#" title="Prague">Prague link</a>
<a href="#" title="Budapest">Budapest link</a>

JavaScript:

window.onload = function(){
    var anchors = document.getElementsByTagName('a');
    for(var i=0; i<anchors.length; i++){
        anchors[i].onclick = function(){
            document.getElementById("myinput").value = this.getAttribute("title");
            return false;
        }
    }
};

Try this:

Html

<a href="javascript:void(0);" id="Budapest" onclick="changeTitle('Budapest')">Budapest</a>
<a href="javascript:void(0);" id="Prague" onclick="changeTitle('Prague ')">Prague       
</a>

<input type="text" id="test"/>

Javascript

<script>
function changeTitle(changeVal){
  var link_text = $('#'+changeVal).text();
  $("#test").val(link_text);   
}
</script>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top