简体   繁体   中英

Rails implementation of input tag firing event on value change

I was wondering if there is some cleaner way to implement event firing on input tag value change (i want it to fire every time character is entered/deleted) and make these values visible in controller other than using ajax?

So the way I know now is implementing JavaScript snippet which would attach addEventListener to input element (like here ) and would make ajax call to initial rails controller to pass the new input tag value. However ajax feels like too much as opposed to if there would be something native in rails, I just can't seem to find it.

If you need anything from browser going out to server (written in any language) without refreshing the page, Ajax is the way to go. Now-a-days, fetch would be another alternative, which works in similar manner.

If you need every key-stroke to be sent to server (controller), you should add a keyup event listener. In the event listener function, make an Ajax/fetch call to the endpoint, and return relevant information from your controller.

Do remember to include a timestamp in the requests, and send them back in response though. In most such scenarios, you'd want to be differentiate between "what is new" vs "what is stale", in case user types too fast. Due to network delays, responses typically do not come back in same order as the requests were made in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM