Я вполне уверен, что понимаю проблему с вашим исходным кодом - невозможность предотвратить действие по умолчанию при использовании кнопки.Я немного изменил код и добавил функцию ajax, которая позволяла бы отправлять данные формы без перезагрузки страницы.По сути тот же код, но переписанный для использования внешних прослушивателей событий, а не встроенных вызовов обработчиков событий.Надеюсь, я помогу.
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
/*
this is to emulate whatever code you have in
the form action /riu/riu-01/riu001.php
*/
exit( json_encode( $_POST ) );
}
?>
<!DOCTYPE html>
<html>
<head>
<title>You have got to have a title...</title>
<style>
button{ width: 100%;height:45px;background-color: dodgerblue }
.bbb{}
fieldset{border:none;}
</style>
<script>
document.addEventListener('DOMContentLoaded',()=>{
/*
presumably this will be in riu003.js
------------------------------------
*/
let counter = 0; // the counter to be incremented.
let url=location.href; // change this to "/riu/riu-01/riu001.php"
const submity=function(e){
/*
explicitly prevent the default form submission
*/
e.preventDefault();
/* The payload is a FormData object */
let payload=new FormData( document.querySelector('form[name="myform"]') );
/*
The callback can do far more than this...
*/
let callback=function( r ){
alert( r )
}
/*
send the ajax request to the backend PHP script.
The actual url used will not be `location.href`
according to the original code...
*/
ajax.call( this, url, payload, callback );
};
/* a variation on the createElemented function */
const create=function(type,attributes,parent){
try{
let el = ( typeof( type )=='undefined' || type==null ) ? document.createElement( 'div' ) : document.createElement( type );
let _arr=['innerhtml','innertext','html','text'];
for( let x in attributes ) if( attributes.hasOwnProperty( x ) && !~_arr.indexOf( x ) ) el.setAttribute( x, attributes[ x ] );
if( attributes.hasOwnProperty('innerHTML') || attributes.hasOwnProperty('html') ) el.innerHTML=attributes.innerHTML || attributes.html;
if( attributes.hasOwnProperty('innerText') || attributes.hasOwnProperty('text') ) el.innerText=attributes.innerText || attributes.text;
if( parent!=null ) typeof( parent )=='object' ? parent.appendChild( el ) : document.getElementById( parent ).appendChild( el );
return el;
}catch( err ){
console.warn( err.message );
}
};
/* ultra basic ajax function to send a POST request */
const ajax=function(url,payload,callback){
let xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if( this.status==200 && this.readyState==4 )callback.call( this, this.response );
}
xhr.open('POST',url,true);
xhr.send(payload);
};
const addfielderbutt=function(e){
counter++;
/* explicitly prevent the default action being triggered */
e.preventDefault();
/* create a fieldset and append new children to it */
let fieldset=create( 'fieldset', {}, document.getElementById('aaa') );
/* add the children */
create( 'textarea',{ 'class':'upt_' + counter, name:'positiveuse_' + counter },fieldset );
create( 'textarea',{ 'class':'unt_' + counter, name:'negativeuse_' + counter },fieldset );
create( 'textarea',{ 'class':'dpt_' + counter, name:'positivedisuse_' + counter },fieldset );
create( 'textarea',{ 'class':'dnt_' + counter, name:'negativedisuse_' + counter },fieldset );
};
/*
Bind the event handlers to the buttons
*/
document.querySelector( 'button.bbb' ).addEventListener( 'click', addfielderbutt );
document.querySelector( 'button[ type="submit" ]' ).addEventListener( 'click', submity );
});
</script>
</head>
<body>
<form name='myform' method='post'>
<div id='aaa'>
<!-- generated content will appear here -->
</div>
<button class='bbb'>Add Fields</button>
<button type='Submit' value='submit'>SUBMIT</button>
</form>
</body>
</html>