cheerio icon indicating copy to clipboard operation
cheerio copied to clipboard

Can't get button value using the val function

Open ribeirobreno opened this issue 1 year ago • 5 comments

In the latest version (0.22.0), getting a button value is not possible with the .val() function.

import * as cheerio from "cheerio";

let ch = cheerio.load(`<form><button value="something">I'm a button</button></form>`);
console.log(ch('button').val());
console.log(ch('button').attr('value'));

The code snippet above will return:

undefined
something

To match jQuery behavior, it should return:

something
something

ribeirobreno avatar Jul 30 '24 01:07 ribeirobreno

Adding more context, jQuery documentation is a little misleading in stating that "val" will try to get the value from a specific list of tags. In fact, it will get the "value" attribute from anything that has this attribute in their DOM prototype. See:

  • https://github.com/jquery/jquery/blob/3.7.1/src/attributes/val.js (only checks for the attribute existence, handles set vs get and handles special cases)
  • https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/elements#value (aside from object and fieldset, all tags listed here should return it's value from a .val function call)
  • https://developer.mozilla.org/en-US/docs/Web/HTML/Element#forms (more form elements)
  • https://developer.mozilla.org/en-US/docs/Web/API/HTMLButtonElement#htmlbuttonelement.value https://developer.mozilla.org/en-US/docs/Web/API/HTMLDataElement/value https://developer.mozilla.org/en-US/docs/Web/API/HTMLOutputElement (those have a value attribute, so they will get read by .val)

ribeirobreno avatar Jul 30 '24 02:07 ribeirobreno

Thanks for the links! Happy to accept PRs for this.

fb55 avatar Aug 09 '24 15:08 fb55

Hey @fb55 can I work on the issue?

PRASUN-SITAULA avatar Oct 01 '24 12:10 PRASUN-SITAULA

For sure! PRs welcome

fb55 avatar Oct 01 '24 12:10 fb55

Thanks @fb55 Could you please let me know which part of the source code I should change for? Thanks!

PRASUN-SITAULA avatar Oct 01 '24 13:10 PRASUN-SITAULA