Using jQuery / Javascript to preprocess online forms before saving them

I need help with preprocessing online forms before submitting and storing them in a database. This form is actually executed using the ChronoForms component in Joomla 3.1. The form is created using HTML, and processing is performed using jQuery / JavaScript using the Load JS action inside the OnLoad event (for those familiar with ChronoForms).

The simplified form is as follows:

<form name="online_form" id="online_form"> <select name="period_year" id="period_year"> <option value="1">1</option> <option value="2">2</option> </select> <select name="period_month" id="period_month"> <option value="1">1</option> <option value="2">2</option> </select> <input type="hidden" name="period" id="period"/> <input type="submit" id="submit_form"/> </form> 

What I want to do when users submit the form, the values ​​for period_year and period_month are combined in the text string "x year and y months" and made as a value for the period. Only the period will be stored in the database, not period_year and period_month.

I tried using an event listener to submit for the form, but it didn't seem to work:

 window.addEvent('domready', function() { $('online_form').addEventListener('submit', function() { var period_year = $('period_year').value; var period_month = $('period_month').value; $('period').value=period_year+' year and '+period_month+' months'; } ); } 

Another alternative was to use the onchange attribute in the select element as follows, but it didn't seem to me either:

 .... <select name="period_year" id="period_year" onchange="process()">...</select> <select name="period_month" id="period_month" onchange="process()">...</select> .... 

For the head:

 function process() { $('period').value=period_year+' year and '+period_month+' months'; }; 

What I did wrong? Or are there other right ways to do this?

+4
source share
2 answers

# required to select items with id

 $('#online_form').submit(function() { //-^---here $('#period').val(period_year+' year and '+period_month+' months'); //-^---here )}; 
+2
source

You need to use # for ID Selector ("#id") also change value to val() . value is used with the DOM object, and the selector will return a jQuery object. If you want to use a value, use [0] indexer to convert the jQuery object to a DOM object.

 $('#online_form').addEventListener('submit', function() { $('#period').val(period_year+' year and '+period_month+' months'); //$('period')[0].value=period_year+' year and '+period_month+' months'; } ); 
+1
source

Source: https://habr.com/ru/post/1481320/


All Articles