how to pass twig code from javascript to twig file? - javascript

I want to create a registration form for agent, but one agent should be able to register how many agent they want.
User complete fields (name, surname etc..) and they must answer the question:
Would you like add new agent? -> look add code:
<div class="form-group">
<label for="new_agent">Would you like add new agent:</label>
<div class="radio new_agent_div">
<label class="radio-inline">
<input type="radio" name="new_agent" id="new_agent" value="1"> Yes
</label>
<label class="radio-inline">
<input type="radio" name="new_agent" id="new_agent2" value="0" > No
</label>
</div>
</div>
<div class="add-agents"></div>
if they checked Yes I run jquery code:
jQuery(document).ready(function($) {
$(".new_agent_div").change(function(){
var html = [
' <div class="form-group">',
' <label for="name">First Name</label>',
' <input type="text" class="form-control" name="name" id="name" value="{{app.request.get("name")}}" placeholder="">',
' {% if validation["name"][0] is defined %}',
' <span class="help-block">',
' <span class="glyphicon glyphicon-exclamation-sign"></span>',
' {{validation["name"][0]}}',
' </span>',
' {% endif %}',
' </div>'
].join('');
if ($('#new_agent').is(':checked')) {
$('.add-agents').html(html);
}
if ($('#new_agent2').is(':checked')) {
$('.add-agents').html('');
}
});
});
After that should be displayed again if add new user...
What's a problem? When I click 'Yes' I received Twig tags as string. Look:
twig tags
What should I do? Maybe some filters or something like this?

Why you did not put the html by default and hide/show when the radio value changes?
<div class="form-group">
<label for="new_agent">Would you like add new agent:</label>
<div class="radio new_agent_div">
<label class="radio-inline">
<input type="radio" name="new_agent" id="new_agent" value="1"> Yes
</label>
<label class="radio-inline">
<input type="radio" name="new_agent" id="new_agent2" value="0" > No
</label>
</div>
</div>
<div class="add-agents" style="display:none;">
<div class="form-group">
<label for="name">First Name</label>
<input type="text" class="form-control" name="name" id="name" value="{{app.request.get("name")}}" placeholder="">
{% if validation["name"][0] is defined %}
<span class="help-block">
<span class="glyphicon glyphicon-exclamation-sign"></span>
{{validation["name"][0]}}
</span>
{% endif %}
</div>
</div>
And then the js looks like
jQuery(document).ready(function($) {
$(".new_agent_div").change(function(){
if ($('#new_agent').is(':checked')) {
$('.add-agents').css("display" , "block");
}
if ($('#new_agent2').is(':checked')) {
$('.add-agents').css("display" , "none");
}
});
});

Related

Function that generates multiple dynamic ID's with a defined pattern

I am trying to make a function that generates multiple dynamic ID's with a defined pattern, how do I do that?
followup: Vue.js: How to generare multiple dynamic ID's with a defined pattern
Details:
I am creating a dynamic school-test application. When the button "Add question" is clicked, a
div with 4 input fields and 4 radio buttons are generated. Each input and radio button needs to have an ID.
So far, the function generates a value, that I hope can be used as an ID. Every radio button has a
name, that makes it possible to only choose one option in the group it belongs to. With every button
click on the "Add Question" button (which is a radio button), this particular "name" is used to count button clicks. With the help of the counter, the dynamic ID for the "question" input field and "options" input fields
(that is connected to the radio buttons) is generated in this pattern:
Example
Testtitle-Question-Option
JavaScriptQ1 (Question)
JavaScriptQ1O1 (Option)
JavaScriptQ1O2
JavaScriptQ1O3
JavaScriptQ1O4
Since there is a div that is generated when the test is launched, and the ID is only generated by button clicks one
div won't get it's ID's. It seems that there is only one question in the ID's in the example above when it's in fact two!
I am currently not using saveTest(), which will be used to save the test into a mySQL database, but it may be used to solve this!
1. I want that one extra "group of ID's" is generated, so each input field gets an ID, but how do I do that?
2. When this matter is solved, how do I generate unique ID's for the radio buttons?
3. How do I then do to use the generated values as ID's. How do I "attach" them to their input fields and radio buttons?
4 Is there any other, better ways to solve this? The ID's has to follow a certain pattern since they will be saved in
a database and then be used to correct the tests.
I know that it's a rather complex issue, but I have tried to explain as good as possible.
I advise that you look at the jsfiddle instead! Click on Add Question and you will see how it works.
var name=1;
$("body").on('click', '#radioAddQuestion', function () {
var singleQuestionModule = "singleQuestionModule";
var question = $(".module:first").clone()
.find("input:text").val("").end();
var question_label = $(".question-label:first").clone();
$(question).find(':radio').prop('checked', false);
$(question_label).insertBefore(".options-label:last");
$(question).insertBefore(".options-label");
$(question).find(':radio').attr('name', "n" + name);
// Here is where the ID value is currently generated:
name++;
let questionId = theTitle + "Q" + name;
console.log(questionId);
for (a = 1; a <= 4; a++) {
let optionId = theTitle + "Q" + name + "O" + a;
console.log(optionId);
}
console.log(name)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<div id="singleQuestionModule">
<form class="form-group">
<div class="input-group input-group">
<label id="wQuestionLabel" class="form-control-label" style="width: 540px;" for="wQuestion">Question:</label>
</div>
<!-- The Question Inputfield that needs ID-->
<div class="input-group input-group">
<input type="text" class="form-control" aria-label="" id="wQuestion" style="width: 540px;">
</div>
<div class="input-group input-group">
<label id="questionOptions" class="form-control-label" style="width: 540px;" for="wQuestion">Enter avaible options:</label>
</div>
<!-- The radio buttons and option input fields that need ID's-->
<div class="input-group input-group">
<span class="input-group-addon">
<input type="radio" name= "q" id="option1" aria-label="">
</span>
<input type="text" class="form-control" aria-label="" style="width: 540px;">
</div>
<div class="input-group input-group">
<span class="input-group-addon">
<input type="radio" name="q" id="option4" aria-label="">
</span>
<input type="text" class="form-control" aria-label="" style="width: 540px;">
</div>
<!-- The Add and Save Test Buttons-->
<span class="options-label"></span>
<br>
<div class="form-group row">
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-success" id="radioAddQuestion">
<input type="radio" #click="counter += 1" name="options" autocomplete="off">Add Question</label>
<label class="btn btn-success">
<input type="radio" name="options" id="radioSaveTest" value="saveTest()" autocomplete="off">Save Test </label>
</div>
</div>
I changed the script. just have look on that. It will generate dynamic ID for all controls that you have been used.
var name=1;
var theTitle="online";
$("body").on('click', '#radioAddQuestion', function () {
name++;
$(".dynamicform").append(createQuestion(name));
});
$(".dynamicform").append(createQuestion(name));
function createQuestion(name){
var dynamic=`<span class="module">
<legend class="col-form-legend col-sm-10"></legend>
<div class="input-group input-group">
<label id="wQuestionLabel" class="form-control-label" style="width: 540px;" for="wQuestion">Question:</label>
</div>
<div class="form-group row">
<div class="input-group input-group">
<!-- The Question Inputfield that needs ID-->
<input type="text" class="form-control" aria-label="" id="${theTitle + "Q" + name}" style="width: 540px;">
</div>
</div>
<div class="form-group row">
<div class="input-group input-group">
<label id="questionOptions" class="form-control-label" style="width: 540px;"
for="wQuestion">Enter
avaible options:</label>
</div>
</div>
<!-- The radiobuttons and option inputfields that needs ID's-->
<div class="form-group row">
<div class="input-group input-group">
<span class="input-group-addon">
<input type="radio" name="${theTitle +"rg"+name}" id="${theTitle + "Q" + name + "O" + "1"}" aria-label="">
</span>
<input type="text" id="${theTitle + "Q" + name + "input" + "1"}" class="form-control" aria-label="" style="width: 540px;">
</div>
</div>
<div class="form-group row">
<div class="input-group input-group">
<span class="input-group-addon">
<input type="radio" name="${theTitle +"rg"+name}" id="${theTitle + "Q" + name + "O" + "2"}" aria-label="">
</span>
<input type="text" id="${theTitle + "Q" + name + "input" + "2"}" class="form-control" aria-label="" style="width: 540px;">
</div>
</div>
<div class="form-group row">
<div class="input-group input-group">
<span class="input-group-addon">
<input type="radio" name="${theTitle +"rg"+name}" id="${theTitle + "Q" + name + "O" + "3"}" aria-label="">
</span>
<input type="text" id="${theTitle + "Q" + name + "input" + "3"}" class="form-control" aria-label="" style="width: 540px;">
</div>
</div>
<div class="form-group row">
<div class="input-group input-group">
<span class="input-group-addon">
<input type="radio" name="${theTitle +"rg"+name}" id="${theTitle + "Q" + name + "O" + "4"}" aria-label="">
</span>
<input type="text" id="${theTitle + "Q" + name + "input" + "4"}" class="form-control" aria-label="" style="width: 540px;">
</div>
</div>
</span>
`;
return dynamic;
}
#singleQuestionModule {
margin-left: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<div id="singleQuestionModule">
<form class="form-group">
<div class="d-flex justify-content-center">
<fieldset class=" form-group row">
<div class="dynamicform">
<!--Dynamic form comes here-->
</div>
<span class="options-label"></span>
<br>
<div class="form-group row">
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-success" id="radioAddQuestion">
<input type="radio" #click="counter += 1" name="options" autocomplete="off">Add Question</label>
<label class="btn btn-success">
<input type="radio" name="options" id="radioSaveTest" value="saveTest()" autocomplete="off">Save
Test </label>
</div>
</div>
</fieldset>
</div>
</form>
</div>
Jsfiddle : https://jsfiddle.net/d9tfk1u6/
Why don't you just put a first id on the elements that are already there? If you want to use the first id that comes out of the id generation function, either change the id generation function so it skips that, or use an onload to add it.
This seems like the obvious solution to the problem, so maybe I've misunderstood it.

Data From Svc Not Modeling Into View Elements AngularJS

I have a view that is modeled to functions which pass data through to a database. This is all working and I see the data coming back when called, but it is not pre-populating the fields in my view when it comes back. I've been banging my head for a while on this. Everything is modeled (from what I can tell) properly.
I have stepped through the JS code below in Chrome and see the data being assigned to my $scope variables from the data.XXX return.
But, after load finishes, it's not preselecting my radio button or populating the fields with the data. Any help greatly appreciated.
Here is the View:
<div class="notification-container">
<form name="notificationForm" class="form-horizontal" ng-submit="saveQrNotifications()">
<div class="list-unstyled">
<input id="text" ng-model="NotificationMethods.NotificationMethodId" ng-change="notifyVisible()" name="text" type="radio" ng-value="1001"> Text Message<br>
<input id="email" ng-model="NotificationMethods.NotificationMethodId" ng-change="notifyVisible()" name="email" type="radio" ng-value="6"> Email<br>
<input id="voice" ng-model="NotificationMethods.NotificationMethodId" ng-change="notifyVisible()" name="voice" type="radio" ng-value="1003"> Voice<br>
<input id="nocontact" ng-model="NotificationMethods.NotificationMethodId" ng-change="notifyVisible()" name="nocontact" type="radio" ng-value="1000"> Do Not Contact<br>
</div>
<div class="col-md-12 notification-fields" ng-show="notifyFieldVisibility == true">
<div class="col-md-12" ng-if="NotificationMethods.NotificationMethodId == '1001'">
<label class="notication-input">Text Number</label>
<span class="clearfix"></span>
<input class="form-control area-code" type="text" ng-model="NotificationMethods.NotificationTextAreaCode" placeholder="(555)" required>
<input class="form-control phone-number" type="text" ng-model="NotificationMethods.NotificationTextPhoneNumber" placeholder="555-5555" required>
</div>
<div class="col-md-12" ng-if="NotificationMethods.NotificationMethodId == '6'">
<label class="notification-input" for="email">E-mail Address
<input class="form-control" id="email" name="email" type="text" ng-model="NotificationMethods.NotificationEmailAddress" placeholder="ex.me#example.com" required>
</label>
</div>
<div class="col-md-12" ng-if="NotificationMethods.NotificationMethodId == '1003'">
<label class="notication-input">Voice Number </label>
<span class="clearfix"></span>
<input class="form-control area-code" type="text" ng-model="NotificationMethods.NotificationVoiceAreaCode" placeholder="(555)" required>
<input class="form-control phone-number" type="text" ng-model="NotificationMethods.NotificationVoicePhoneNumber" placeholder="555.5555" required>
<label class="small">Ext.</label>
<input class="form-control extension" type="text" ng-model="NotificationMethods.NotificationVoiceExtension" placeholder="555">
</div>
<span class="clearfix"></span>
<div ng-show="notifyLoading" class="text-center" style="margin-top: 10px;">
<i class="fa fa-spinner fa-spin"></i> Saving...
</div>
<div class="col-md-12">
<button type="submit" class="btn btn-primary notification-btn">Save Notifications</button>
</div>
</div>
</form>
</div>
Here is my controller:
DATA COMING FROM DB:
if (data.StatusCode == "SUCCESS") {
$scope.refill = data;
//$scope.deliverTypes = data.DeliveryTypes;
$scope.showError = false;
$scope.submitRefill = true;
$scope.findRefillStatus = userMessageService.QuickRefillMessage(data.Prescriptions[0]);
$scope.isRefillable = data.Prescriptions[0].IsRefillable;
$scope.prescription.noPrescription.$valid = true;
$scope.loading = false;
$scope.NotificationMethods.NotificationEmailAddress = data.NotificationEmailAddress;
$scope.NotificationMethods.NotificationMethodId = data.NotificationMethodId;
$scope.NotificationMethods.NotificationTextAreaCode = data.NotificationTextAreaCode;
$scope.NotificationMethods.NotificationTextPhoneNumber = data.NotificationTextPhoneNumber;
$scope.NotificationMethods.NotificationVoiceAreaCode = data.NotificationVoiceAreaCode;
$scope.NotificationMethods.NotificationVoicePhoneNumber = data.NotificationVoicePhoneNumber;
$scope.NotificationMethods.NotificationVoiceExtension = data.NotificationVoiceExtension;
}
Figured it out. I was declaring the controller on the view used in ng-include. Removing that and letting the view inherit controller from surrounding view solved issue.

How to submit form with partially read only inputs with jQuery?

I made a form in jQuery + Django which has only one input active and the others are read only. There is a button which when clicked activates all the input boxes and the whole form is then editable. However, before clicking the button only one input is there and I want to be able to submit the form in that state. But I want all the other values to be submitted too, as they are readonly that should not be a problem.
Here's my JS:
$('#addInventoryForm').on('submit', function(event) {
event.preventDefault();
$('#name').focus();
add_to_inventory();
});
function add_to_inventory() {
console.log("add to inventory is working!")
$.ajax({
url : "/new/item/add/",
type : "POST",
data : { upc : $('#upc').val(), name : $('#name').val(), qty : $('#qty').val(), add_qty : $('#add_qty').val(), reorder_qty : $('#reorder_qty').val(), dp : $('#dp').val(), mrp : $('#mrp').val(), supplier : $('#supplier').val() },
success : function(data) {
console.log(data);
$('#extra').html(data);
console.log("success");
}
});
}
The url in the above code points to the following view:
def NewItemAdd(request):
if request.method == "POST":
upc = request.POST['upc']
name = request.POST['name']
if 'qty' in request.POST:
qty = request.POST['qty']
add_qty = request.POST['add_qty']
reorder_qty = request.POST['reorder_qty']
dp = request.POST['dp']
mrp = request.POST['mrp']
if 'supplier' in request.POST:
supplier = Supplier.objects.get(name=request.POST['supplier'])
if 'qty' not in request.POST:
qty = 0
if 'supplier' in request.POST:
defaults = {'name': name, 'qty': int(qty) + int(add_qty), 'reorder_qty': reorder_qty, 'dp': dp, 'mrp': mrp, 'supplier': supplier, 'user': request.user}
else:
defaults = {'name': name, 'qty': int(qty) + int(add_qty), 'reorder_qty': reorder_qty, 'dp': dp, 'mrp': mrp, 'user': request.user}
inv, created = Item.objects.update_or_create(upc=upc, defaults=defaults)
supplier_list = Supplier.objects.all()
return render(request, "alpha/new-item-add.html", {'suppliers': supplier_list})
The template used with this view is as follows:
<div class="container">
<div class="form-group">
<label class="control-label col-xs-1" for="name">Name:</label>
<div class="col-xs-9">
<input type="text" class="form-control" id="name" name="name" placeholder="" tabindex="2"/>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-1" for="qty">Current Quantity:</label>
<div class="col-xs-2">
<input type="number" class="form-control" id="qty" name="qty" placeholder="" readonly/>
</div>
<label class="control-label col-xs-1" for="add_qty">Add Quantity:</label>
<div class="col-xs-2">
<input type="number" class="form-control" id="add_qty" name="add_qty" placeholder="" tabindex="3"/>
</div>
<label class="control-label col-xs-offset-1 col-xs-1" for="reorder_qty">Reorder Quantity:</label>
<div class="col-xs-2">
<input type="number" class="form-control" id="reorder_qty" name="reorder_qty" placeholder="" tabindex="4"/>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-1" for="dp">DP:</label>
<div class="col-xs-2">
<input type="text" class="form-control" id="dp" name="dp" placeholder="" tabindex="5"/>
</div>
<label class="control-label col-xs-1" for="mrp">MRP:</label>
<div class="col-xs-2">
<input type="text" class="form-control" id="mrp" name="mrp" placeholder="" tabindex="6"/>
</div>
<label class="control-label col-xs-offset-1 col-xs-1" for="reorder_qty">Supplier:</label>
<div class="col-xs-2">
<select name="supplier" id="supplier" class="btn btn-default form-control" tabindex="7">
{% for supplier in suppliers %}
<option value="{{ supplier }}" {% if supplier.name == item.supplier.name %}selected{% endif %}>{{ supplier.name }}</option>
{% endfor %}
</select>
</div>
</div>
<div class="form-group">
<div class="col-xs-offset-1 col-xs-9">
<input type="submit" value="Submit" class="form-control btn btn-primary" tabindex="8"/>
</div>
</div>
</div>
I want to be able to submit the form when the inputs are readonly as well as when I click a button and activate all the inputs. Can anyone find anything wrong with the above code?
The edit button removes the readonly attribute from all the inputs of the form. So before submitting the form I trigger a click on the edit button. It's almost instantaneous and the problem is solved.
$("#edit").trigger("click");

How to use ternary operator to change value of ng-model in AngularJS?

I have one text field and one checkbox. If checkbox is true I want value from address field to become after the checkbox, if false the field should be empty. I tried ternary operator with ng-class and many more, but no luck. What would be the best and working solution for that?
jsfiddle
<form name="form" ng-app>
<div class="form-group form-group-lg required">
<label class="col-md-2 control-label">Address:</label>
<div class="col-md-10" ">
<input type="text " name="address " class="form-control " ng-model="address " ng-minlength="4 " placeholder="Address " required>
</div>
</div>
<div class="form-group form-group-lg">
<label class="col-md-2 control-label">Return Address</label>
<div class="col-md-10">
<div class="input-group">
<span class="input-group-addon">
<!--condition ? first_expression : second_expression; -->
<input type="checkbox" ng-model="isReturnAddress" ng-change="">
</span><!--condition ? first_expression : second_expression; -->
<input type="text" class="form-control" ng-model="address">
</div>
{{isReturnAddress}}
</div>
</div>
<button type="submit " class="btn btn-primary btn-large " ng-click="submitted=true ">Submit</button>
you should use two input elements in this case. Like
<input ng-if="isReturnAddress" type="text" class="form-control" ng-model="address">
<input ng-if="!isReturnAddress" type="text" class="form-control">
and in your controller, please check
if($scope.isReturnAddress){
var address = $scope.address;
}
See working fiddle here

How to hide/show a text-box base on other text-box in Laravel 4?

Goal
show email confirm when a user start editing the email section.
hide the email confirm text-box if the user doesn't touch it.
Don't do anything if the user only edit the username part.
Edit Form
username* __________________________
email* __________________________
email confirm* _____________________
HTML/BLADE
<div class="form-group">
<label class="col-sm-3 control-label required ">Username </label>
<div class="col-sm-9 form-group float-label-control ">
{{ Form::text('username', isset($user->username) ? $user->username : '' , array('id'=>'form-field-icon-2')); }}
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label required ">Email </label>
<div class="col-sm-9 form-group float-label-control ">
{{ Form::text('email', isset($user->email ) ? $user->email : '' , array('id'=>'form-field-icon-2')); }}
</div>
</div>
HTML
<label> Username </label><br>
<input type="text" name="username"><br>
<label> Email </label><br>
<input type="text" name="email" id="email"><br>
<label id="l-email-conf" > Email Confirm </label><br>
<input type="text" name="email_confirm" disabled="disabled" id="email-conf">
JS
$('#l-email-conf').hide();
$('#email-conf').hide();
$('#email').on('input', function (event) {
var text = $(this).val();
if (text === '') { // If email is empty
$('#email-conf').prop('disabled', true);
} else {
$('#email-conf').prop('disabled', false);
$('#email-conf').show();
$('#l-email-conf').show();
}
});
JSFiddle
Inline javascript could be an elegant solution if you don't want to write a function.
onkeyup and onkeydown events will do the job and you don't need jQuery
<form>
<p>
<label for="email">Email</label>
<input type="text" name="email" id="email" onkeyup="this.parentNode.nextElementSibling.style.display = 'block';" onkeydown="this.parentNode.nextElementSibling.style.display = 'none';"/>
</p>
<p id="confirm-email">
<label for="confirm">Confirm email</label>
<input type="text" name="confirm" id="confirm"/>
</p>
</form>
CSS:
#confirm-email {
display: none;
}
Example: jsFiddle
Say this is your HTML -
<input type="text" name="username">
<input type="text" name="email" id="email">
<input type="text" name="email_confirm" disabled="disabled" id="email-conf">
<script>
// Use jQuery event handlers
$('#email').on('input', function (event) {
var text = $(this).val();
if (text === '') { // If email is empty
$('#email-conf').prop('disabled', true);
} else {
$('#email-conf').prop('disabled', false);
}
});
</script>
jsFiddle
P.S. - U can toggle hide/show instead of disabling also.

Categories