MCPcopy Create free account
hub / github.com/gawel/pyquery / val

Method val

pyquery/pyquery.py:974–1069  ·  view source on GitHub ↗

Set the attribute value:: >>> d = PyQuery(' ') >>> d.val('Youhou') [ ] Get the attribute value:: >>> d.val() 'Youhou' Set the selected values for a `select` element with the `multiple` attribute::

(self, value=no_default)

Source from the content-addressed store, hash-verified

972 # HTML #
973 ########
974 def val(self, value=no_default):
975 """Set the attribute value::
976
977 >>> d = PyQuery('<input />')
978 >>> d.val('Youhou')
979 [<input>]
980
981 Get the attribute value::
982
983 >>> d.val()
984 'Youhou'
985
986 Set the selected values for a `select` element with the `multiple`
987 attribute::
988
989 >>> d = PyQuery(''&#x27;
990 ... <select multiple>
991 ... <option value="you"><option value="hou">
992 ... </select>
993 ... ''&#x27;)
994 >>> d.val(['you', 'hou'])
995 [<select>]
996
997 Get the selected values for a `select` element with the `multiple`
998 attribute::
999
1000 >>> d.val()
1001 ['you', 'hou']
1002
1003 """
1004 def _get_value(tag):
1005 # <textarea>
1006 if tag.tag == 'textarea':
1007 return self._copy(tag).html()
1008 # <select>
1009 elif tag.tag == 'select':
1010 if 'multiple' in tag.attrib:
1011 # Only extract value if selected
1012 selected = self._copy(tag)('option[selected]')
1013 # Rebuild list to avoid serialization error
1014 return list(selected.map(
1015 lambda _, o: self._copy(o).attr('value')
1016 ))
1017 selected_option = self._copy(tag)('option[selected]:last')
1018 if selected_option:
1019 return selected_option.attr('value')
1020 else:
1021 return self._copy(tag)('option').attr('value')
1022 # <input type="checkbox"> or <input type="radio">
1023 elif self.is_(':checkbox,:radio'):
1024 val = self._copy(tag).attr('value')
1025 if val is None:
1026 return 'on'
1027 else:
1028 return val
1029 # <input>
1030 elif tag.tag == 'input':
1031 val = self._copy(tag).attr('value')

Calls

no outgoing calls