2

I am having troubles pulling the value from a link. It's a CSS formatted page and I would really prefer to use a <a> than a <button>.

<button value="1" onclick="showDetails(this.value)">This works</button>
<a value="2" onclick="showDetails(this.value)">This doesn't work</a>

};
        xmlhttp.open("GET","getdetails.php?q="+str,true);
        xmlhttp.send();

How can I get the value of <a> when it is clicked and not having it go somewhere?

Adriano
  • 3,788
  • 5
  • 32
  • 53

4 Answers4

5

Only a select few elements, like <input>s, <textarea>s, and <button>s can have value properties:

console.log(
  document.querySelector('a').value
);
<a value="val">a</a>

If you have to use the value attribute, use the getAttribute method instead of dot notation:

console.log(
  document.querySelector('a').getAttribute('value')
);
<a value="val">a</a>

Another option would be to use data attributes instead, which would be more appropriate than value="s when working with an <a>:

console.log(
  document.querySelector('a').dataset.value
);
<a data-value="val">a</a>

(also make sure to attach your event handlers properly using Javascript if at all possible - inline handlers are generally considered to be pretty poor practice - try using addEventListener)

To use addEventListener, select your a, and call addEventListener on it. For example, if your <a> has an id of details:

const details = document.querySelector('#details');
details.addEventListener('click', () => {
  showDetails(details.dataset.value);
});

function showDetails(str) {
  console.log('showing details for ' + str);
}
<a id="details" data-value="thevalue">click for details</a>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • `document.querySelector('a')['value']` should works too – Piterden Oct 18 '18 at 02:29
  • Dot notation is preferable to bracket notation. Bracket notation should generally only be used if it can't be expressed with dot notation, such as if you're accessing a dynamic property name, or a property name with an illegal character like `-`. – CertainPerformance Oct 18 '18 at 02:30
  • Who sad it? Preferable by whom? The fastest is the bracket notation with doublequotes. – Piterden Oct 18 '18 at 02:32
  • @Piterden https://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets `Dot notation is faster to write and clearer to read.` – CertainPerformance Oct 18 '18 at 02:33
  • @Tony See edit, select the element and call `addEventListener` on it – CertainPerformance Oct 18 '18 at 02:35
  • @CertainPerformance it's only your opinion. It shouldn't be right for everyone. https://github.com/rwaldron/idiomatic.js/ – Piterden Oct 18 '18 at 02:36
  • @Piterden It's not just my opinion, that's how it's considered pretty much universally. Even most linters will reject code that uses bracket notation unnecessarily. Why use `['` and `']` when instead of both, you can just use a single `.`? You sometimes see inexperienced coders from languages that use bracket notation use something like `['foo']` instead of `.foo`, but it's not something that should be recommended. – CertainPerformance Oct 18 '18 at 02:39
  • @Piterden Even your own link looks to prefer dot notation to bracket notation. Sorry, I don't understand. – CertainPerformance Oct 18 '18 at 02:43
  • I'm still having trouble trying to get it to work, even with the event handler. –  Oct 18 '18 at 02:44
  • @Tony Ok, I converted it into a runnable snippet, seems to work just fine – CertainPerformance Oct 18 '18 at 02:46
  • @CertainPerformance - Thank you so much, but my PHP generates new buttons with new data-values (and unique ids) - what's a way I can handle this? –  Oct 18 '18 at 02:56
  • Never mine, showDetails(this.dataset.value) seems to work! –  Oct 18 '18 at 02:59
  • @CertainPerformance my link's general idea is to be consistent. If you started to write with the same way, you should continue with that way till the end of your app development. – Piterden Oct 18 '18 at 05:24
1

You can write a Javascript function to get the value from the link as follows:

function showDetails(a){
  let value = a.getAttribute("value");
  // view value
  console.log(value)
}
<!--<button value="1" onclick="showDetails(this)">Button link</button>-->
<a value="2" onclick="showDetails(this)">Anchor link</a>
Dalton Whyte
  • 657
  • 1
  • 8
  • 15
0

Your issues has 2 parts:

#1: Use of correct attribute

You should not use the value attribute in <a> tag, as it's not a valid attribute for HTML standard; try to use data-val instead. Attributes starting with data- allow us to store extra information on standard, semantic HTML elements without other hacks.

Example:

<a data-val="2" onclick="showDetails(this)">Test</a>

For the JS function, it can be written as:

function showDetails(obj) {
    console.log(obj.dataset.val); // 2
}

References: https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes


#2: Prevent the <a> gets redirected

The initial choice of using <a> is incorrect, as <a> is designed to: (1) redirect to other page via hyperlink specified; or (2) go to certain section in the page using anchor name.

However, you can still stop the redirection using JavaScript (though not suggested). Edit your onclick function as below:

<a data-val="2" onclick="showDetails(this); return false;">Test</a>

Note the return false is added.

p.s. for better coding standard, you should separate JS from HTML structure.

Raptor
  • 53,206
  • 45
  • 230
  • 366
-1

Anchor tag does not have a value attribute, you can read about it in mdn. If you need to assign a value to an anchor tag you can use custom data attribute data-*. In order to get values from data-* in your javascript function can try something like this

const anchor = document.querySelector('a');
const str = anchor.data.value;

And then use it in your ajax logic.

const url = 'getdetails.php';
const params = `q=${str}`;
const http = new XMLHttpRequest();

http.open('GET', `${url}?${params}`, true);
// ... other logic
Mario
  • 4,784
  • 3
  • 34
  • 50