Proper display of user editing form (CRUD model) with checkbox - javascript

I'm making a simple CRUD model with input checkbox. I have no problems on server side, everything is fine. I use NodeJS +MongoDB. But I have problem in editing existing user. When I edit an existing user with a checked checkbox( I get JSON object with parameter checked=true ) how should I display it using JS? This is part of my users.js file in /routes/ folder
var express = require('express');
var router = express.Router();
var User = require('../../models/User');
var rest = require('restler');
router.get('/adduser', function(req, res){
var user = new User();
user.contacts.push({phone: '', email: ''});
rest.get('http://localhost:3000/api/adduser').on('complete', function(data) {
res.render('users/add', { title: 'Add New Users' , n: user});
});
});
And this is views/users/fields.jade part of file for better understanding:
.form-group
label.col-sm-2.control-label(for='email') E-mail:
.col-sm-10
input(type="email", placeholder="email", name="email", value = n.contacts[0].email,required)
.form-group
.col-sm-offset-2.col-sm-10
input#enabled(type="checkbox",style='text-align: center; vertical-align: middle;',placeholder="", name="enabled", value = n.enabled)
| Enable user
So my problem is that I don't understand how I should display that checkbox is really checked when loading existing user.
If user is checked attribute n.enabled=true and if not n.enabled=false. So if user is checked on load of that user I need the input filed to be checked.
I've tried it to do the following way, but it wrote me that n wasn't defined...and I don't know how to pass n as the parameter for that function:
$(document).ready(function(){
if(n.enabled=="true"){$("enabled").toggle(this.checked);}
});

In fields.jade, change value = n.enabled to checked = (n.enabled ? 'checked' : '')

Use # for id-selectors and use n.enabled directly to hide or show your element like,
$("#enabled").toggle(n.enabled);
//-^ prepend # before id selectors
toggle() will show/hide your element, To check uncheck use the prop() like
$(document).ready(function(){
$("#enabled").prop("checked",n.enabled);
});

Related

Pass variable with subvariable from JQuery to Flask app

I have a Flask that uses WTForms and Jquery to take from the user "input" fields in a form and shows "select" fields to the user. Jquery is used to filter the select fields shown to the user based on what they enter in the input fields. In order to filter the select fields, I need to take what the user enters in the input fields and send it to the Flask app.
These are the form fields -
class TableName(FlaskForm):
schema = StringField('Schema', validators=[DataRequired()], id = 'schema_name')
table = StringField('Table', validators=[DataRequired()], id = 'table_name')
class QaForm(FlaskForm):
test_table_in = FormField(TableName, id = 'test_table')
prod_table_in = FormField(TableName, id = 'prod_table')
This is the JQuery -
$(function() {
var tables = {
test_table: $('test_table_in-schema_name').val() + "." + $('test_table_in-table_name').val(),
prod_table: $('prod_table_in-schema_name').val() + "." + $('prod_table_in-table_name').val()
};
var fields = {
test: [$('#select_test_join_key'), $('#select_test_dimensions')],
prod: [$('#select_prod_join_key'), $('#select_prod_dimensions')]
};
fields.test.forEach(item => updateFields(tables.test_table, item));
fields.prod.forEach(item => updateFields(tables.prod_table, item));
function updateFields(table, field) {
var send = {
table: tables.table
};
$.getJSON("{{url_for('_get_fields') }}", send, function(data) {
//do something
});
}
});
When the user enters a "test_table", the test table should get passed to _get_fields() and when the user enters a prod_table, that value should get sent to _get_fields(). Test_table and prod_table are two form fields, each consisting of two subfields, "schema" and "table" that are combined to create one field in the format "schema.table".
Function _get_fields() in Flask view to receive the table name -
#app.route('/_get_fields/')
def _get_fields():
table = request.args.get('table', type=str)
fields_query = f"""select column_name AS Fields from information_schema.columns WHERE
table_name = '{table}' group by 1 limit 10;"""
conn.execute(fields_query)
result = conn.fetchall()
return jsonify(result)
Potential errors:
It's the request_args.get() function in the Flask view that I believe is not referring correctly to the JQuery variables. I've tried 'test_table', 'prod_table', and others but none of these have worked so far. I'm using the "name" of the input form elements to create the table variables - I'm wondering if that may be a part of the issue as well. Any thoughts or suggestions?

How to do update in listing for web by using firebase

I am creating admin panel in website and I am using firebase as a database in backend.I am able to display listing but when I click on the particular listing there status should change from 'pending' to 'accept' but it doesnt.I dont know where I did mistake.Please give suggestion and I attach js file and database screenshot
pl.js
var firebaseheadingRef = firebase.database().ref().child("user");
firebaseheadingRef.on('child_added',datasnapshot=>{
var title= datasnapshot.child("listing").child("title").val();
var userid= datasnapshot.child("username").val();
var type= datasnapshot.child("listing").child("title").val();
var publisheddate= datasnapshot.child("listing").child("publish").val();
var expirydate= datasnapshot.child("listing").child("expire").val();
$("#tablebody").append("<tr><td>"+title+"</td><td>"+userid+"</td><td>"+type+"</td><td>"+publisheddate+"</td><td><button type=button id=accept onclick=accept()>Accept</button><button type=button>Reject</button></td></tr>");
});
function accept()
{
firebaseheadingRef.on('child_changed',datasnapshot=>{
datasnapshot.child("listing").child("status").update({"status":"accept"});
setCommentValues(postElement, data.key, data.val().text, data.val().author);
});
}
database
listing display picture where I click on accept button then update of status should done
There are two places where you need to change your code:
First, in the code that generates the table, you have to pass the id of the node to the function call, as follows. You get the node id with the key property of the DataSnapshot.
.....
$("#tablebody").append("<tr><td>"+title+"</td><td>"+userid+"</td><td>"+type+"</td><td>"+publisheddate+"</td><td><button type=button id=accept onclick=accept('" + datasnapshot.key + "')>Accept</button><button type=button>Reject</button></td></tr>");
...
And secondly you have to write your accept() function in such a way it updates the database value, with the set() method. Like the following
function accept(userId) {
var nodeRef = firebase.database().ref("/user/" + userId + "/listing/status");
return nodeRef.set('accept');
}

How to submit dynamically created hidden variables using Jquery

I have created a dynamic table. DEMO to my project.
I have placed this dynamic table in the form under a div named 'box'
<div id="box">
</div>.
I am creating dynamic hidden variables table using Jquery which I need to store in DB. This is how I am creating the hash to submit to server.
criteria = $('form_name').serialize(true);
criteria = Object.toJSON(criteria);
// Build the object to store the parameters for the AJAX post request
parameters = {
title : $('report_title').value,
description : $('report_description').value,
criteria : criteria
}
// Make the AJAX post request
new Ajax.Request( URL, {
method: 'post',
parameters: parameters,
onSuccess: function( response ) {
$('messageSpan').innerHTML = response.responseText;
$('spinner').style.display='none';
}
});
I am not able to capture the dynamically created values in the criteria.
How to solve this?
In the dynamically created section, I tried adding a submit button and see if the values can be fetched. I am able to fetch and iterate all the hidden variables.
$('#jquerysaveButton').click(function(){
jsonObj = [];
$("input[id=rubric_cell]").each(function () {
var id = "cell_" + row + "_" + col;
item = {}
item["id"] = id;
item["selected_rubric"] = $(this).val();
jsonObj.push(item);
});
console.log(jsonObj); //I am getting the required values here
});
How to get these values in the criteria = $('form_name').serialize(true);. Am I doing some thing wrong? Please help me. thanks in advance.
DEMO to my project
You need to make sure that your hidden input fields have a name attribute set otherwise $.serialize will not process them.

Tokeninput save new tag to database

I am trying to save a new tag entered in input field that was not there in database and want to save that created tag on form submit. Here is my controller which is sending the autocomplete list to the tokeninput input field:
def tags = {
def foundTags = Tag.findAllByTagnameIlike("${params.q}%")
def output = []
foundTags.each {
output.add([id: it.id, name: it.tagname]) // assumes Tag has an id field exposed
}
if(output.size()==0){
def c = Tag.createCriteria()
def maxId = c.get {
projections {
max('id')
}
}
output.add([id:(maxId+1),name:params.q])
}
render output as JSON
}
My jQuery script is:
<script type="text/javascript">
$(document).ready(function () {
$("#my-text-input").tokenInput("${createLink(controller: 'product', action: 'tags')}",{theme: "facebook",allowFreeTagging:"true"});
});
</script>
Now when I submit the form, i get params.tags as the ids of those newly entered tags in the input field.But actually these IDs do not exist and are created by output.add([id:(maxId+1),name:params.q]) just for the reason that tokeninput requires it to be there.
So how do i get the tag names in the params.tags instead of the ids? Infact i require something like this map ["id1":"tagname1","id2":"tagname2".....]. So how do i get the actual tagname instead of the id fields in the server side action which persists the form params?
Make use of the tokenValue parameter during set up.
e.g. In jQuery
<script type="text/javascript">
$(document).ready(function () {
$("#my-text-input").tokenInput("${createLink(controller: 'product', action: 'tags')}",{
theme: "facebook",
allowFreeTagging:"true",
tokenValue:"name"
});
});
</script>
This will submit an array of names instead of IDs. If you need both name's and id's, you're probably best adding a custom attribute to each token through an onAdd parameter, and then setting that to the tokenValue.

Codeigniter 2.1, Jquery - delete all checkboxes checked

At the moment, I am confused by this problem. How can I delete all files that have been checked?
This is the function to select or unselect checkboxes:
var del_selected = $('.zute_strane_izmena_obrisi_sve'),
del_url = del_selected.attr('href'),
selektuj_sve = $('.zute_strane_izmena_selektuj_sve'),
slike = $('.zuta_strana_trenutne_slike'),
box = slike.find(':checkbox'),
selektovane_slike = [];
selektuj_sve.on('click', function(){
$(this).text(box.is(':checked') ? 'Selektuj Sve Slike' : 'Deselektuj Sve Slike');
box.attr('checked', !box.is(':checked'));
});
Jquery for now (it is working without error):
del_selected.on('click', function(e){
box.filter(':checked').each(function(){
selektovane_slike.push($(this).val());
$(this).parent().slideUp('fast');
});
data = JSON.stringify(box.serializeArray(), null, 2);
console.log(data);
e.preventDefault();
});
Where to go from here?
You need to make an AJAX request to the server to delete the files. You need to be very careful about file permissions. The web server either needs to have permission to delete, or it needs to defer the action to a process that does (such as by writing the request to the database or a queue).

Categories