Django does not safe the values of the BooleanFields - javascript

I have the following form with few boolean fields:
class RegistrationForm(UserCreationForm):
guardianSource = forms.BooleanField(widget=forms.CheckboxInput(attrs={'id':'guardianSource'}),required=False)
bbcSource = forms.BooleanField(required=False)
independentSource = forms.BooleanField(required=False)
categoryCoronaVirus = forms.BooleanField(required=False)
categoryPolitics = forms.BooleanField(required=False)
categorySport = forms.BooleanField(required=False)
#Telling the registration form what kind of data we are going to be modelling/ what the form needs to look like
class Meta:
model = Account
fields = ("username", "password1", "password2", "guardianSource", "bbcSource", "independentSource", "categoryCoronaVirus", "categoryPolitics", "categorySport")
The register template looks as following:
<form class="form-signin" method="POST">{% csrf_token %}
<h1 class="h3 mb-3 font-weight-normal">Register</h1>
<label for="username" class="sr-only">Username</label>
<input type="text" name="username" id="username" class="form-control" placeholder="User name" required autofocus>
<label for="inputPassword1" class="sr-only">Password</label>
<input type="password" name="password1" id="inputPassword1" class="form-control" placeholder="Password" required>
<label for="inputPassword2" class="sr-only">Password</label>
<input type="password" name="password2" id="inputPassword2" class="form-control" placeholder="Confirm Password" required>
<br>
<div class="form-control">
<p><b>Please choose news sources!</b></p>
<label for="guardianSource" >The Guardian</label>
<input type="checkbox" name="source" id="guardianSource">
<br>
<label for="bbcSource" >BBC News</label>
<input type="checkbox" name="source" id="bbcSource">
<br>
<label for="independentSource" >The Independent</label>
<input type="checkbox" name="source" id="independentSource">
</div>
<br>
<div class="form-control">
<p><b>Please choose news category!</b></p>
<label for="categoryCoronaVirus" >Corona Virus</label>
<input type="checkbox" name="category" id="categoryCoronaVirus">
<br>
<label for="categoryPolitics" >Politics</label>
<input type="checkbox" name="category" id="categoryPolitics">
<br>
<label for="categorySport" >Sport</label>
<input type="checkbox" name="category" id="categorySport">
</div>
{% for field in registration_form %}
<p>
{% for error in field.errors %}
<p class="alert alert-danger card-header text-center flashit"> {{ error }}</p>
{% endfor %}
</p>
{% endfor %}
{% if registration_form.non_field_errors %}
<div style="color:red;">
<p>{{registration_form.non_field_errors}}</p>
</div>
{% endif %}
<h6 class="text-muted">
NOTE: You <b>MUST</b> select at least 1 choice for each!!!
</h6>
<div id="error_message"> </div>
<button class="btn btn-lg btn-primary btn-block" type="submit" onclick="valthisform()">Register</button>
</form>
There is a JavaScript function that checks if at least 1 checkbox for category and 1 for source is selected before submitting the form:
function valthisform(){
var guardianSource = document.getElementById("guardianSource").checked;
var bbcSource = document.getElementById("bbcSource").checked;
var independentSource = document.getElementById("independentSource").checked;
var checkedSource = false;
var categoryCoronaVirus = document.getElementById("categoryCoronaVirus").checked;
var categoryPolitics = document.getElementById("categoryPolitics").checked;
var categorySport = document.getElementById("categorySport").checked;
var checkedCategory = false;
if(guardianSource ===true || bbcSource===true || independentSource===true){
checkedSource = true;
}
if(categoryCoronaVirus===true || categoryPolitics===true || categorySport===true){
checkedCategory = true;
}
if(checkedSource ===false && checkedCategory===false){
document.getElementById('error_message').innerHTML = '<div class="alert alert-danger card-header text-center flashit"><strong>Warning!</strong> No source and category selected!</div>';
event.preventDefault();
}
else if(checkedSource ===false ){
document.getElementById('error_message').innerHTML = '<div class="alert alert-danger card-header text-center flashit"><strong>Warning!</strong> No source selected!</div>';
event.preventDefault();
}
else if(checkedCategory===false){
document.getElementById('error_message').innerHTML = '<div class="alert alert-danger card-header text-center flashit"><strong>Warning!</strong> No category selected!</div>';
event.preventDefault();
}
}
The problem is: when I don't check any checkbox when registering the JavaScript function works as it is supposed to - it prevents saving the data into the database and prints whatever it supposed to. After printing the warning message, I check few boxes and submit the form. Form submits and redirects to home page, however, once I look into the database the checked boolean values are not saved - they are all False.
My django view for register is:
def registration(request):
context = {}
if request.user.is_authenticated: # If user is logged in, redirect to home screen, they cannot register again!
return redirect('home')
if request.POST:
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password1')
account = authenticate(username=username, password=raw_password)
login(request, account)
return redirect('home')
else:
context['registration_form'] = form
else: # GET request
form = RegistrationForm()
context['registration_form'] = form
return render(request, 'accounts/register.html', context)
EDIT:
I finally found the bug after going through the commits on git and comparing files to earliest commits.
Basically the code from the register template:
<label for="guardianSource" >The Guardian</label>
<input type="checkbox" name="source" id="guardianSource">
<br>
<label for="bbcSource" >BBC News</label>
<input type="checkbox" name="source" id="bbcSource">
<br>
<label for="independentSource" >The Independent</label>
<input type="checkbox" name="source" id="independentSource">
</div>
<br>
<div class="form-control">
<p><b>Please choose news category!</b></p>
<label for="categoryCoronaVirus" >Corona Virus</label>
<input type="checkbox" name="category" id="categoryCoronaVirus">
<br>
<label for="categoryPolitics" >Politics</label>
<input type="checkbox" name="category" id="categoryPolitics">
<br>
<label for="categorySport" >Sport</label>
<input type="checkbox" name="category" id="categorySport">
</div>
I have renamed for some reason the name attribute of each checkbox.
After changing the values to:
<label for="guardianSource" >The Guardian</label>
<input type="checkbox" name="guardianSource" id="guardianSource">
<br>
<label for="bbcSource" >BBC News</label>
<input type="checkbox" name="bbcSource" id="bbcSource">
<br>
<label for="independentSource" >The Independent</label>
<input type="checkbox" name="independentSource" id="independentSource">
</div>
<br>
<div class="form-control">
<p><b>Please choose news category!</b></p>
<label for="categoryCoronaVirus" >Corona Virus</label>
<input type="checkbox" name="categoryCoronaVirus" id="categoryCoronaVirus">
<br>
<label for="categoryPolitics" >Politics</label>
<input type="checkbox" name="categoryPolitics" id="categoryPolitics">
<br>
<label for="categorySport" >Sport</label>
<input type="checkbox" name="categorySport" id="categorySport">
</div>
It works.

You seem to repeat some of the model fields in your form again. That's not necessary and might cause this error. If you use the following in models.py and forms.py, then calling the save() method should save all fields in your database.
models.py:
class Account(AbstractUser):
guardianSource = models.BooleanField(blank=True, null=True)
bbcSource = models.BooleanField(blank=True, null=True)
independentSource = models.BooleanField(blank=True, null=True)
categoryCoronaVirus = models.BooleanField(blank=True, null=True)
categoryPolitics = models.BooleanField(blank=True, null=True)
categorySport = models.BooleanField(blank=True, null=True)
forms.py:
class RegistrationForm(UserCreationForm):
class Meta:
model = Account
fields = ("username", "password1", "password2", "guardianSource", "bbcSource", "independentSource", "categoryCoronaVirus", "categoryPolitics", "categorySport")
widget = {'guardianSource': forms.CheckboxInput(attrs={'id':'guardianSource'})}

Related

How to validate input field with numbers only using javascript?

I am new to Javascript, I need to validate the input field. I wish to enter only numbers, not allowing alphabets or special characters. I need to show the error message below the input field. Validation rules for the input field are:
Should be numbers only
Numbers should be greater than 1 and less than available quantity.
I have form with three input fields, available quantity, quantity and bid price.
Validation on value entered on quantity field should be greater than 1 and less than the available quantity is working fine. But I need to enter only numbers using javascript.
What I have tried is
<form method="post" action="/truckianBidSave/{{id}}" id="reviewForm">
<input type="hidden" name="_token" value="{{csrf_token()}}" />
<input type="hidden" name="user_name" value="{{auth_user().first_name}}" />
<!-- <div class="form-group row">
<label class="col-sm-4 col-form-label">Select Milege Gap: </label>
<div class="col-sm-8">
<select class="form-select" name="mileage" id="mileage" onchange="getOption()">
<option>Select </option>
{% for p in product_data %}
<option value="{{p.number_of_products}},{{p.number_of_products_sold}},{{p.mileage_gap}}">{{p.mileage_gap}}</option>
{% endfor %}
</select>
</div>
</div>-->
<div class="form-group row">
{% set total=0 %}
{% set sold=0 %}
{% for p in product_data %}
{% set total =total+p.number_of_products %}
{% set sold=sold+p.number_of_products_sold %}
{% endfor %}
{% set available=total-sold %}
<label for="available" class="col-sm-4 col-form-label">Available Quantity: </label>
<div class="col-sm-8">
<input type="text" class="form-control" id="available" readonly name="available_qty" value={{available}} />
</div>
</div>
<div class="form-group row">
<label for="qty" class="col-sm-4 col-form-label"> Quantity: </label>
<div class="col-sm-8">
<input type="text" id="qty" name="qty" class="form-control" oninput="checkInput(this);" required />
<p id="qty-msg">
</p>
</div>
</div>
<div class="form-group row">
<label for="inputBid" class="col-sm-4 col-form-label">Enter Bid Price</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="inputBid" name="bid" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');"/>
</div>
</div>
<div class="form-group text-center">
<input type="submit" class="btn btn-primary" id="btn" name="send" value="Send" disabled="disabled">
</div>
</form>
Javascript code:
function checkInput(item)
{var available=document.getElementById("available");
var msg=document.getElementById("qty-msg");
if(parseInt(item.value)>parseInt(available.value) )
{
item.value='';
msg.innerHTML="* Value must be less than Availabe quantity "+available.value ;
msg.style.color="red";
}
else if(parseInt(item.value)<1)
{
item.value='';
msg.innerHTML="* Value must be greater than 1" ;
msg.style.color="red";
}
else if('/^[A-Za-z]+$/'.test(item.value))
{ alert('hi');
item.value='';
msg.innerHTML="* Only numbers allowed" ;
msg.style.color="red";
}
How to not allow alphabets and special characters in input filed using javascript.
Use this instead of your pattern
!(/^[0-9]{1,}$/.test(item.value))
It'll return true if the value contains a string, otherwise, it'll return false.
You may use <input type="number"> for the 'qty' input. See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number for details.
A javascript filter like
document.getElementById('qty').addEventListener('keydown',
function(event){
if(!event.key.match(/^[0-9]$/)){
event.preventDefault();
}
}
);
is never perfectly safe, i.e., it will not work on some old browsers or mobile browsers.

Laravel stripe and cashier no such payment method

I am using Laravel 7 and i am integratng stripe with cashier and i am facing issue
No such PaymentMethod: 'tok_1HBxFdEft5GkDC4v7ZnPgW5Y'
I am using custom checkout forms Html code is
<form class="rt-formtheme rt-paymentmethodform" method="POST" action="{{route('subscripe.process')}}" id="subscribe-form">
#csrf
<div class="div-stripe-errors col-12" style="margin-top: 30px;"></div>
<fieldset>
<legend>Choose your card</legend>
<!-- <div class="form-group">
<button type="submit" class="rt-btn rt-savebtn">Save</button>
</div> -->
<div class="form-group">
<span class="rt-radio">
<input type="radio" name="radiobutton" id="visa">
<label for="visa"><img src="{{asset('images/visa.png')}}" alt=""></label>
</span>
</div>
<div class="form-group">
<span class="rt-radio">
<input type="radio" name="radiobutton" id="american-express">
<label for="american-express"><img src="{{asset('images/american-express.png')}}" alt=""></label>
</span>
</div>
<div class="form-group">
<label>Card Number</label>
<input type="text" name="cardnumber" class="form-control" placeholder="1234 5678 9012 3456" data-stripe="number">
</div>
<div class="rt-twocols">
<div class="form-group">
<div class="rt-twoinputfieldholder">
<div class="rt-twoinputfieldbox">
<label>Expiry Month</label>
<input type="text" name="expirymonth" class="form-control" placeholder="MM" data-stripe="exp-month">
</div>
<div class="rt-twoinputfieldbox">
<label>Expiry Year</label>
<input type="text" name="expiryyear" class="form-control" placeholder="YY" data-stripe="exp-year">
</div>
</div>
</div>
<div class="form-group">
<label>CVC</label>
<input type="text" name="cvv" class="form-control" placeholder="123" data-stripe="cvc">
</div>
</div>
<div class="form-group margin-zero rt-savecarddetailbox">
<span class="rt-checkbox">
<input type="checkbox" name="savecarddetail" id="savecarddetail">
<label for="savecarddetail">Save Card Details</label>
</span>
<button type="submit" class="rt-btn float-right">Checkout</button>
</div>
</fieldset>
</form>
and js code is
<script src="https://js.stripe.com/v2/"></script>
<script>
Stripe.setPublishableKey('{{ env("STRIPE_KEY") }}');
$(document).ready(function(){
$('#subscribe-form').submit(function(e){
var form = $(this);
form.find('button').prop('disabled', true);
Stripe.card.createToken(form, function(status, response) {
if (response.error) {
form.find('.div-stripe-errors').text(response.error.message).addClass('alert alert-danger');
form.find('button').prop('disabled', false);
} else {
// append the token to the form
form.append($('<input type="hidden" name="cc_token">').val(response.id));
// debugger
// submit the form
form.get(0).submit();
}
});
e.preventDefault();
});
});
Route is
Route::post('/subscribe_process', 'Dashboard\CheckoutController#subscribeProcess')->name('subscripe.process');
and controller method is
public function subscribeProcess(Request $request)
{
try{
$cc_token = $request->cc_token;
$user = Auth::user();
$user->newSubscription('Main','Monthly')->create($cc_token);
alert()->success('User Updated Successfully', 'Success');
return \redirect()->back();
}catch(\Exception $ex){
return $ex->getMessage();
}
}
and i also create plan on stripe dashboard
when i create a subscription it show error No such payment method i am new in stripe kindly help me
"No such..." errors are usually caused by either a mismatch in API keys (e.g. using a mixture of your test plus live keys) or by trying to access objects that exist on a different account (e.g. trying to perform an operation from your platform account on an object that was created on a connected account).

Django dropdown selection is not working when submit button is pressed

I have a dropdown selection and 'submit' button in the page. Some fields disappears upon specific dropdown selection. I can hide/show all other fields but except password field. Whenever I hide the password field with a jquery the submit button doesnot work.
following are my code files.
HTML template django
< script >
$(document).ready(function() {
$('#type').change(function(eventObject) {
if ($(this).val() == 'sercomm') {
$('.sample').show();
$('.sample_netip').show();
$('.sample_password').show();
$('.sample_username').hide();
} else {
$('.sample').show();
$('.sample_password').show();
$('.sample_netip').hide();
}
}).change();
});
<
/script>
<form class="form-horizontal" method="post" role="form">{% csrf_token %} {# dropdown#}
<div class="form-group">
<label class="col-sm-3 control-label">{% trans "Mode" %}</label>
<div class="col-sm-6">
<select name="type" class="form-control" id="type">
<option value="ex1" selected>{% trans "ex1" %}</option>
<option value="ex2">{% trans "ex2" %}</option>
</select>
</div>
</div>
{# end of dropdown#}
<div class="form-group sample">
<label class="col-sm-3 control-label">{% trans "Name" %}</label>
<div class="col-sm-6">
<input type="text" class="form-control" name="name" placeholder="{% trans " Name " %}" maxlength="20" id="name" required pattern="[a-zA-Z0-9\.\-_]+">
</div>
</div>
<div class="form-group sample">
<label class="col-sm-3 control-label">{% trans "Management Network IP Address" %}</label>
<div class="col-sm-6">
<input type="text" class="form-control" name="ipaddr" value="192.168.255.129" maxlength="20" required pattern="^(25[0-5]|2[0-4]\d|[0-1]?\d?[1-9]|[0-1]?[1-9][0])(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$">
</div>
</div>
<div class="form-group sample_netip">
<label class="col-sm-3 control-label">{% trans "Radio Network IP Address" %}</label>
<div class="col-sm-6">
<input type="text" class="form-control" name="netipaddr" value="192.168.255.129" maxlength="20" required pattern="^(25[0-5]|2[0-4]\d|[0-1]?\d?[1-9]|[0-1]?[1-9][0])(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$">
</div>
</div>
<div class="form-group sample_username">
<label class="col-sm-3 control-label">{% trans "User Name" %}</label>
<div class="col-sm-6">
<input type="text" class="form-control" name="username" value="" maxlength="48" required pattern="[a-zA-Z0-9\.\-_]+">
</div>
</div>
<div class="form-group sample_password">
<label class="col-sm-3 control-label">{% trans "Password" %}</label>
<div class="col-sm-6">
<input type="password" class="form-control" name="password" value="" maxlength="48" required pattern="[a-zA-Z0-9\.\-_]+">
</div>
</div>
<div class="form-group sample">
<label class="col-sm-3 control-label">{% trans "Description" %}</label>
<div class="col-sm-6">
<input type="text" class="form-control" name="description" value="" maxlength="48" pattern="[a-zA-Z0-9\.\-_ ]+">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">{% trans "Close" %}</button>
<button type="submit" class="btn btn-primary" name="create" value="1">{% trans "Create" %}</button>
</div>
</form>
forms.py goes here
import re
from django import forms
from django.utils.translation import ugettext_lazy as _
class BaseStationDetailsForm(forms.Form):
type = forms.ChoiceField(required=True, choices=(('nokia', 'nokia'), ('sercomm', 'sercomm')))
name = forms.SlugField(error_messages={'required': _('No base station name has been entered')}, max_length=20)
ipaddr = forms.IPAddressField(error_messages={'required': _('Invalid IP Address')})
netipaddr = forms.IPAddressField(error_messages={'required': _('Invalid IP Address')}) #test
username = forms.CharField(error_messages={'required': _('No user name has been entered')}, max_length=48)
password = forms.CharField(error_messages={'required': _('No password has been entered')}, max_length=48)
description = forms.CharField(required=False, max_length=48)
models.py
from django.db import models
class BaseStation(models.Model):
name = models.CharField(max_length=20)
address = models.IPAddressField()
ipaddress = models.IPAddressField() #tests
username = models.CharField(max_length=48)
password = models.CharField(max_length=48)
description = models.CharField(max_length=48, blank=True, null=True)
status = models.IntegerField(default=0)
def __unicode__(self):
return self.name
views.py (only the create (post) button is gives :
if 'create' in request.POST:
form = BaseStationDetailsForm(request.POST)
if form.is_valid():
data = form.cleaned_data
if basestations and data['name'] in basestation_names:
msg = _("Base Station with this name already exists")
errors.append(msg)
elif ip_addresses and data['ipaddr'] in ip_addresses:
msg = _("IP address " + data['ipaddr'] + " is already assigned to another Base Station")
errors.append(msg)
else:
_type = request.POST.get('type', '')
basestation = BaseStation(name=data['name'],
address=data['ipaddr'],
ipaddress=data['netipaddr'],
username=data['username'],
password=data['password'],
description=data['description'],
status='0')
# test
basestation.save()
return HttpResponseRedirect(request.get_full_path())
else:
for error_key in form.errors:
for error_msg in form.errors[error_key]:
errors.append(error_msg)
### other post button functions code deleted
return render_to_response('basestations.html', locals(), context_instance=RequestContext(request))
Example - I can show /hide username/description, the create button works. Only when password field is hidden, the button does not work.
When you are hiding the password field you also have to remove the required attribute with something like this
$('#password_field').removeAttr('required');​​​​
And then when you show the field add the required again so that the form does not submit without the password.
Your password field have attribute required. Which means that this field is required to submit the form.
To prevent this behavior, during form submission you need to have the following markup.
<div class="col-sm-6">
<input type="password" class="form-control" name="password" value="" maxlength="48" pattern="[a-zA-Z0-9\.\-_]+">
</div>
Mozilla Reference for HTML validations

Save data from form

I want to save the data that I get from my form (html).
I have same fileds in my form and I want to send them from html page to node.js page and from there to mongoDB (mlab) database.
In my node page I use angular to save the data that I gets form user.
I'm using ng-controller to connect to js page, and using ng-model to hold the data that I get in input label.
My problem is that I cant save the data in mongoDB?
Thanks,
html:
<body ng-controller="addController">
<h1 class="text-center">Add Activity</h1>
<form class="form-group" ng-submit="createActivity()">
<div class="form-group">
<div class="col-sm-10">
<label for="inputEmail3" class="col-sm-2 control-label">Title:</label>
<input class="form-control" type="text" placeholder="Title" ng-model="title"></input>
</div>
<div class="col-sm-10">
<label for="inputEmail3" class="col-sm-2 control-label">Age:</label>
<input class="form-control" id="inputEmail3" type="number" placeholder="Age" ng-model="age" min="0" max="16"></input>
</div>
<div class="col-sm-10">
<label for="inputEmail3" class="col-sm-2 control-label">Description:</label>
<textarea class="form-control" id="inputEmail3" type="text" placeholder="Description" ng-model="description"></textarea>
<br>
</div>
<div class="col-sm-10">
<label for="inputEmail3" class="col-sm-2 control-label">Themes:</label>
<input type="radio" name="themes" value="frozen" ng-model="theme">frozen
<input type="radio" name="themes" value="minions" ng-model="theme">minions
<input type="radio" name="themes" value="heroes" ng-model="theme">heroes
<input type="radio" name="themes" value="princess" ng-model="theme">princess
<input type="radio" name="themes" value="piraets" ng-model="theme">piraets
<input type="radio" name="themes" value="none" ng-model="theme">none
<br>
</div>
<div class="col-sm-10">
<br>
<input type="file" name="upload" ng-model="image"></input>
</div>
<div class="col-sm-10">
<br>
<input type="submit" class="btn btn-default" name="send"></input>
</div>
</div>
</form>
js:
var addActivityApp = angular.module('addActivityApp',['$scope','$resource']);
var Activity = $resource('/activities');
var activity = new Activity();
$scope.createActivity=function () {
var activity = new Activity();
activity.title = $scope.title;
activity.age = $scope.age;
activity.description = $scope.description;
activity.theme = $scope.theme;
activity.$save(function (result) {
$scope.activities.push(result);
$scope.title = '';
$scope.age = '';
$scope.description = '';
$scope.theme = '';
});
});
addActivityApp.controller('addController',function($scope) {
$scope.addController = model;
});
You can try the below code. check if you using the same below code on your server side.
app.post('yourserverurl', function(req, res) {
console.log(req.body) //Here all form data will display
var InsertData = req.body;
db.collection('restaurants').insertOne(InsertData,function(err, result) {
assert.equal(err, null);
console.log("Inserted a document into the collection.");
callback();
});
});
if you share the whole code which you have written in server side, so i can simplify it more

HTML unknown element, at least for me [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm developing a data-recollection view in HTML and i've seen the need of creating something like this:
I explain, it's a shitty paint image, so, there is an input where user can introduce data and if he clicks the "+" button it will appear another one, just with the same mechanism.
Is there any element in HTML that makes that or should i create it on my own?
Edit:
I've been developing the form following an angular tutorial and I've got a problem.
This is what my view shows:
Below the label hijos, it should appear a button just like the one in dominio label. Don't have any idea of why is this happening. There is another problem also. The add button should add an input in case of dominio label and a select in case of hijos (if it was correctly showed). At the moment it does nothing. Here is the code I wrote.
HTML part:
<section name="nuevoMovimiento" class="row-fluid">
<form class="form-horizontal text-left">
<fieldset>
<div id="legend">
<legend class="">New entry table</legend>
</div>
<div class="row-fluid">
<div class="col-md-4">
<div class="control-group">
<label class="control-label" for="id">Identificador:</label>
<input type="text" id="id" class="input" name="id" placeholder="Introduzca el ID" ng-model="controlET.nuevaTE.id">
</div>
<div class="control-group">
<label class="control-label" for="desc">Descripción:</label>
<div class="controls">
<textarea id="desc" name="desc" class="textarea" placeholder="Escriba una breve descripción" ng-model="controlET.nuevaTE.descripcion">
</textarea>
</div>
</div>
<div class="control-group">
<label class="control-label" for="tipo">Tipo:</label>
<select name="tipo" id="tipo" class="select" ng-options="" ng-model="controlET.nuevaTE.tipo"></select>
</div>
<div class="control-group">
<label class="control-label" for="tipo_vis">Tipo de visualización:</label>
<select name="tipo_vis" id="tipo_vis" class="select" ng-options="" ng-model="controlET.nuevaTE.tipo_visualizacion"></select>
</div>
</div>
<div class="col-md-4">
<div class="control-group">
<label class="control-label" for="visible">Visible</label>
<input type="radio" name="visible" id="visible" value="true" ng-model="controlET.nuevaTE.visible">Sí
<input type="radio" name="visible" id="visible" value="false" ng-model="controlET.nuevaTE.visible">No
</div>
<div class="control-group">
<label class="control-label" for="valor">Valor:</label>
<input type="text" id="valor" class="input" name="valor" placeholder="Introduzca el valor" ng-model="controlET.nuevaTE.valor">
</div>
<div class="control-group">
<label class="control-label" for="enabled">Enabled:</label>
<input type="text" id="enabled" class="input" name="enabled" placeholder="Introduzca algo" ng-model="controlET.nuevaTE.enabled">
</div>
<div class="control-group">
<label class="control-label" for="obligatorio">Obligatorio:</label>
<input type="radio" name="obligatorio" id="obligatorio" value="true" ng-model="controlET.nuevaTE.obligatorio">Sí
<input type="radio" name="obligatorio" id="obligatorio" value="false" ng-model="controlET.nuevaTE.obligatorio">No
</div>
</div>
<div class="col-md-4">
<div class="control-group">
<label class="control-label" for="dominio">Dominio:</label>
<div class="controls">
<ul class="unstyled">
<li ng-repeat="dominio in controlET.dominioRecollect">
<input type="text" ng-model="dominio.text">
</li>
</ul>
<form ng-submit="controlET.funciones.addDominio()">
<input class="btn-primary" type="submit" value="add">
</form>
</div>
</div>
<div class="control-group">
<label class="control-label" for="hijos">Hijos:</label>
<div class="controls">
<ul class="unstyled">
<li ng-repeat="hijos in controlET.hijosRecollect">
<select id="hijos" name="hijos" ng-options="te.id for te in controlET.TEs2" ng-model="hijos.id">
</li>
</ul>
<form ng-submit="controlET.funciones.addDominio()">
<input class="btn-primary" type="submit" value="add">
</form>
</div>
</div>
</div>
</div>
<div class="col-xs-6 col-centered">
<button style="margin-top: 20px" type="button" class="btn btn-lg btn-primary" ng-click="controlET.funciones.anadirTE()">
<span>Guardar</span>
</button>
</div>
</fieldset>
</form>
</section>
JS part:
(function () {
var ControlETCtrl = function (ETFactory, $scope, $http, $window, $rootScope) {
var scope = this;
scope.titulo = "Entry tables list";
scope.dominioRecollect = [];
scope.hijosRecollect = [];
scope.TEs = ETFactory.getTEs().success(function(data){
scope.TEs = data;
scope.TEs2 = data;
});
scope.TEs2 =[];
scope.nuevaTE = {};
scope.funciones = {};
/*scope.funciones.cargarDatos = function () {
console.log("Entra en cargarDatos()");
$rootScope.$apply(function() {
ETFactory.getTEs().success(function(data){
scope.movimientos = data;
});
});
}*/
scope.funciones.addDominio = function() {
scope.dominioRecollect.push({});
}
scope.funciones.addHijo = function() {
scope.hijosRecollect.push({});
}
scope.funciones.cambiarvalor = function () {
ETFactory.cambiarvalor();
}
scope.funciones.anadirTE = function () {
ETFactory.añadirNuevo(scope.nuevaTE);
}
}
controlCajaApp.controller('ControlETCtrl', ['ETFactory', ControlETCtrl]);
}());
Well that's it, has somebody any idea?
If it's form submitting you're talking about, you might want to look into PHP.
However, if you're just going to be typing in stuff and not doing anything with the data, you can do something like this using jQuery: (http://jsfiddle.net/11x1gq3z/3/)
$(function() {
var lolDiv = $('#inputs');
var i = $('#inputs p').size() + 1;
var addone = '<p><label for="inputs"><input type="text" id="input" size="20" name="input_' + i +'" value="" placeholder="Another box" /></label> Remove</p>';
$('#addbox').live('click', function() { //onclick of div "#addbox"
$(addone).appendTo(lolDiv); //appends new box to lolDiv var
i++; //counter
return false;
});
$('#rembox').live('click', function() {
if( i > 2 ) {
$(this).parents('p').remove(); //removes <p> tags that the boxes are in
i--; //counter but minus this time
}
return false;
});
});
Then for the HTML (Pretty basic):
<h2>Add another box</h2>
<div id="inputs"><p>
<label for="inputs">
<input type="text" id="input" size="20" name="input" value="" placeholder="This is your box, yo" /></label>
</p></div>

Categories

Resources