Selecting and hiding elements with Prototype or Javascript
Anyone up for a Prototype challenge? I am new to Prototype and I am trying to do the following. Would do this in jQuery but the only js library installed is Prototype. Perhaps someone has a javascript solution that would work?
- Strip any whitespace out of the form value (before and after)
- If the input form length is 3 or less hide all the checkPrice.gif images in all rows.
Not sure if this is possible using Prototype.
<form method="get" id="searchForm" name="car" action="some-action">
<input type="text" value="Ford150" name="carPart" id="search" class="textContent">
</form>
<table border="1">
<tr>
<td class="description">Description:</td>
<td class="checkPrice"><p>Type:</p>
<p><a target="_blank" href="link.html"><img src="images/checkPrice.gif"></a></p>
</td>
</tr>
<tr>
<td class="description">Description:</td>
<td class="checkPrice"><p>Type:&l开发者_JS百科t;/p>
<p><a target="_blank" href="link.html"><img src="images/checkPrice.gif"></a></p>
</td>
</tr>
</table>
- Rows repeat
Thanks so much to anyone who can help!
I assume you mean "If the input form value length is 3 or less" since the default input value is not a number.
function updateCheckPrice(event) {
// $F() returns a string
// String.strip() trims whitespace and returns a new string
// String.length is a native property
var length = $F(this).strip().length;
// If length is 3 or less...
var action = length <= 3 ? Element.hide : Element.show;
// Pass the chosen show/hide function to every img element
$$('img[src$=checkPrice.gif]').each(action);
}
document.observe('dom:loaded', function(){
// Update as you type
Event.observe('search', 'keyup', updateCheckPrice);
});
Ok. Trim-function written in pure JS (from http://blog.stevenlevithan.com/archives/faster-trim-javascript):
function trim (str) {
var str = str.replace(/^\s\s*/, ''),
ws = /\s/,
i = str.length;
while (ws.test(str.charAt(--i)));
return str.slice(0, i + 1);
}
How to convert string to number: http://www.javascripter.net/faq/convert2.htm
How to access element's value using Prototype: http://www.prototypejs.org/api/form/element/getValue
How to check is variable - string:
function is_string(input){
return typeof(input)=='string';
}
How to hide element using Prototype: http://www.prototypejs.org/api/element/hide
Now you are ready to solve the task by yourself! ;)
精彩评论