article

Saturday, November 28, 2020

Python Flask Add Remove Input Fields Dynamically with jQuery and save to database MySQLdb

Python Flask Add Remove Input Fields Dynamically with jQuery and save to database MySQLdb

In this tutorial user can add remove input fields and submit form to use input fields values and save to database using mysqldb

install mysqldb
pip install flask-mysqldb https://github.com/alexferl/flask-mysqldb

--
-- Table structure for table `fullnames`
--

CREATE TABLE `fullnames` (
  `id` int(11) NOT NULL,
  `full_name` varchar(255) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

app.py
#app.py
from flask import Flask, render_template, jsonify, request
from flask_mysqldb import MySQL,MySQLdb #pip install flask-mysqldb https://github.com/alexferl/flask-mysqldb

app = Flask(__name__)
  
app.secret_key = "caircocoders-ednalan-2020"
  
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'testingdb'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
mysql = MySQL(app)
      
@app.route('/', methods=['GET', 'POST'])
def index():
    cursor = mysql.connection.cursor()
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    message = ''	
    if request.method == 'POST':
        fullname = request.form.getlist('field[]')
        for value in fullname:	
            cur.execute("INSERT INTO fullnames (full_name) VALUES (%s)",[value])
            mysql.connection.commit()		
        cur.close()
        message = "Succesfully Register"
    return render_template('index.html', message=message)
 

if __name__ == '__main__':
    app.run(debug=True)
templates/index.html
//templates/index.html
<html>  
 <head>  
  <title>Python Flask Add Remove Input Fields Dynamically with jQuery and save to database MySQLdb</title>  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<style>
.input-wrapper div {
    margin-bottom: 10px;
}
.remove-input {
    margin-top: 10px;
    margin-left: 15px;
    vertical-align: text-bottom;
}
.add-input {
    margin-top: 10px;
    margin-left: 10px;
    vertical-align: text-bottom;
}
</style>
 </head>  
 <body>  
  <div style="width:85%;padding:50px;">  
	<h2>Python Flask Add Remove Input Fields Dynamically with jQuery and save to database MySQLdb</h2>	
	{% if message %}
          <div class="alert alert-success">{{message}}</div>
    {% endif %}
	<form method="POST">
		<div class="input-wrapper">
			<div>Name : <br/>
			<input type="text" name="field[]" value=""/>
			<a href="javascript:void(0);" class="add-input" title="Add input"><img src="/static/img/add.png"/></a>
			</div>
		</div>
		<input type="submit" name="cmdsubmit">
	</form>
  
  </div>  
<script>
$(document).ready(function(){
    var max_input_fields = 10;
    var add_input = $('.add-input');
    var input_wrapper = $('.input-wrapper');
    var new_input = '<div><input type="text" name="field[]" value=""/><a href="javascript:void(0);" class="remove-input" title="Remove input"><img src="/static/img/remove.png"/></a></div>';
    var add_input_count = 1; 
	$(add_input).click(function(){
        if(add_input_count < max_input_fields){
            add_input_count++; 
            $(input_wrapper).append(new_input); 
        }
    });
	$(input_wrapper).on('click', '.remove-input', function(e){
        e.preventDefault();
        $(this).parent('div').remove();
        add_input_count--;
    });
});
</script>
 </body>  
</html>  

Related Post