Search code examples
javascriptejshtmxhyperscript

Hyperscript - How do i assign an event to a found element?


I have this event to specific input that works perfectly.

    <input name="company_addresses[0][vat_number]" id="company-profile-vat" type="text" class="form-control"
      value="<%=render?.data?.mes?.company_addresses[0]?.vat_number%>"
      _="on change make a Date called timestamp then put timestamp.toISOString() into the #company-address-updated.value">

But I want to assign this dynamically to several items.

So, on the top of the page, I made this script:

<div id="content-form" _="on load 
repeat for foreignInput in <input[name*='][']:not([name*='][serial_']):not([name*='][updated']), textarea[name*='][']:not([name*='][serial_']):not([name*='][updated']), select[name*='][']:not([name*='][serial_']):not([name*='][updated'])/>
  set inputTarget to foreignInput.name.split('][')[0]+'][updated' 
  repeat for foreignInputUpdateInput in <input[name*=`${inputTarget}`]/>
    log foreignInputUpdateInput 
     
    end
  end
end
"> 

so far, so good, I managed to get all the elements I wanted. However, I want to assign the event to the found element, and I have no idea how. I tried something like:

on change from inputTarget
  make a Date called timestamp then put timestamp.toISOString() into the foreignInputUpdateInput.value
end

but it doesn't work I would like to avoid if possible.


Solution

  • I found a different approach to the situation, instead of using the on-load event, and trying to set the event to a filtered element, I instead set my div to listen to every change, and then I filtered to get the source of the event that I wanted to apply the onChange event:

    <div id="content-form" _="on every change  if event.srcElement.name.split('][').length > 1
                            set inputTargetString to event.srcElement.name.split('][')[0]+'][updated'
                            set inputTargetElement to <input[name*=`${inputTargetString}`]/>
                            if inputTargetElement != undefined
                            make a Date called timestamp then put timestamp.toISOString() into inputTargetElement.value
                            ">