How to add HTML templates in a page? - javascript

I made an template of a price box, and I want that every time that I click a button a new price box shows up in the page.
Just a simple example for my template:
<div>
<h1> Product: {productName} </h1>
</div>
And everytime that I click a button, I pass the name and this template will show in the page.
I was looking and I saw the template tag with javascript and another solutions like Mustache. Which approach would be better and more readable?

Not exactly sure what your asking but this would be very simple using pure javascript. Please see the following code snippet:
function addProduct() {
const productName = document.querySelector('#productName').value;
productName ? document.querySelector('#products').innerHTML += `
<div><h1>Product: ${productName}</h1></div>
` : alert('Enter Product Name');
}
document.querySelector('#add').addEventListener('click', () => addProduct());
<input type="text" id="productName">
<button id="add">Add Product</button>
<div id="products"></div>

Related

How to create a button that works as an output display for input values AS WELL AS copy button for the displayed output?

I am studying a vanilla JS and I would like to create a form wherein the values in the input elements will be displayed inside a button. I am planning to create a form where the user will fill the questions out with their details then those answers will be displayed on the same HTML page formatted in a certain template. Currently, I can display the output however there's no line break per value. Also, since the display is a button element, the user should be able to click it to copy the formatted answers that they can paste on notepad or MS word. Is this even possible in vanilla JS or do I have to learn JS frameworks? Can you share your thoughts?
Example display on a button that can be clicked to copy the below information:
Name: John Smith (line 1)
Age: 99 (line 2)
This is the current output:
This is my current scripts:
<form name="myForm">
Name: <input type="text" id="myName" name="myName">
Age: <input type="number" name="myAge" id="myAge">
<button type="submit" name="createBtn" id="createBtn" onclick="create(); return
false">CREATE</button>
</form>
<div>
<button type="submit" id="copyBtn" onClick="copy(); return false">
<span id="userName"></span>
<span id="userAge"></span>
</button>
</div>
<script>
function create() {
document.getElementById('userName').innerHTML = document.myForm.myName.value;
document.getElementById('userAge').innerHTML = document.myForm.myAge.value;
}
function copy() {
// insert the needed function here
}
</script>

Django Form - Conditional field display using JQuery

This implementation is using Django 4.0 and Bootstrap5 with CrispyForms.
Objective: The user selecting a value in one field determines whether another field is shown or hidden. By default, the conditional field has a value of "No". The impacted field will be shown when the user changes the conditional field to the value of "Yes". Specifically, if the user selects "Yes" for the field Recurring event the field Recurrence pattern will be shown.
Please note that the implementation of Class Based Views in the template is working great. Here's a screenshot of the form (with the conditional field requirement not working):
Existing code (relevant snippets only)
Here's what I have in models.py:
YES_NO_CHOICES = [
('No', 'No'),
('Yes', 'Yes'),
]
RECURRENCE_PATTERN_CHOICES = [
('---', '---'),
('Daily', 'Daily'),
('Weekly', 'Weekly'),
('Monthly', 'Monthly'),
('Yearly', 'Yearly'),
]
class Event(models.Model):
event_name = models.CharField(
max_length=70,
help_text='''Enter a name for the event. This is a required field and is limited to 70 characters.'''
)
recurring_event = models.CharField(
max_length=5,
choices=YES_NO_CHOICES,
default='No',
help_text='''Is this a one off event or will it recur? Selecting Yes will open up additional fields.'''
)
recurrence_pattern = models.CharField(
max_length=10,
choices=RECURRENCE_PATTERN_CHOICES,
default='---',
help_text='''Select the recurrence pattern for this event.'''
)
Here is what I have in forms.py:
class EventStaffSummaryUpdateView(UpdateView):
"""Event Staff Update view - allows staff to change event details"""
model = Event
template_name = 'events/event_staff_summary_form.html'
fields = [
'event_name',
'recurring_event',
'recurrence_pattern',
]
context_object_name = 'event'
In the event_staff_summary.html template (using inheritance) I have:
<div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<div id="event_name">
{{ form.event_name|as_crispy_field }}
</div>
<div id="recurring_event">
{{ form.recurring_event|as_crispy_field }}
</div>
<div id="recurrence_pattern">
{{ form.recurrence_pattern|as_crispy_field }}
</div>
</fieldset>
<div class="form-group pt-4 pb-2">
{% if page_type == 'Update' %}
<button class="btn btn-BlueGray" type="submit">Update Event</button>
{% else %}
<button class="btn btn-BlueGray" type="submit">Create Event</button>
{% endif %}
</div>
</form>
</div>
In the base.html template I am using the Google JQuery link (found on my journey as a simple way of implementing JQuery):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
As you can see with the screenshot, the form itself is displaying perfectly. So models, form and even the html is working to this point. The update class based view is working with the DB. All that remains is to show or hide Recurrence pattern based on the value in the field Recurrence event. Which brings me to...
What have I tried so far?
Of the 10+ JS snippets I've come across and tried, here is the leading candidate that seems to be closest. I really want this to work as it makes sense to me.
<script>
$("#recurring_event").change(function() {
if ($(this).val() === "Yes") {
$('#recurrence_pattern').show();
} else {
$('#recurrence_pattern').hide();
}
});
</script>
Request
Has anyone got suggestions on how I can get this working? I've got requirements for a number of conditionally displayed fields. I'd prefer to not work from checkboxes as typically this client prefers to explicitly have the user click Yes or No as this is clearer to them (they feel there is no chance of ambiguity with a closed question and a yes/no choice).
This requirement of conditional fields in forms is implemented in many instances, so I know I'm not seeking the impossible. I am hoping that there's a simple refinement (or clean up) of the javascript snippet I've posted. I also welcome other JS suggested snippets too.
Thanks in advance for your help.
ANSWER (Feb 27)
Following the issuance of a bounty #Swati came through with a solution posted in a fiddle here: https://jsfiddle.net/L8ke03hc/ As soon as they post the answer I'll award the Bounty. I'd like to thank Tony for coming really close and getting me on the right track. The final piece of the puzzle was the .trigger event to call the change function.
<script>
$(document).ready(function() {
$("#id_recurring_event").change(function() {
if ($(this).val() === "No") {
$('#div_id_recurrence_pattern').hide();
} else {
$('#div_id_recurrence_pattern').show();
}
});
$("#id_recurring_event").trigger("change")
})
</script>
Thanks to all that came through on this one. This was a profound learning experience for me. I really need to spend some time learning JS. That said, I've got the solution. May anyone trying to build conditional logic in Django/CrispyForms benefit from this. I am so grateful for the Open Source community! <3
Update library to
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
Wrap function in a DOM ready event.
Update selector to a <select> (from div). Do this by inspecting DOM.
End result:
(function($){
$(document).ready(function(){
$("#id_recurring_event").change(function() {
if ($(this).val() === "Yes") {
$('#id_recurrence_pattern').show();
} else {
$('#id_recurrence_pattern').hide();
}
});
})
})(jQuery);
You can use trigger() method to achieve this . So, whenever your page gets load called this to execute the change event which is attached on select-box .
Working code :
$(document).ready(function() {
$("#id_recurring_event").change(function() {
if ($(this).val() === "No") {
$('#recurrence_pattern').hide();
} else {
$('#recurrence_pattern').show();
}
});
$("#id_recurring_event").trigger("change")
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="content-section">
<form method="POST">
<fieldset class="form-group">
<div id="event_name">
ABC ..
</div>
<div id="recurring_event">
<select id="id_recurring_event">
<option value="Yes">Yes</option>
<option value="No" selected="true">No</option>
</select>
</div>
<div id="recurrence_pattern">
somethings ..................
</div>
</fieldset>
</form>
</div>

How to add and remove text field on click of a button in angular js

I have generated button using ng-repeat directive in angular js. Now I want to generate a textfield inside a div tag on click of that button.
Example buttons -
Example textfields added on click of it -
I am doing this using innerHTML attribute of div tag, like below -
var txt = document.getElementById("paidby").innerHTML;
document.getElementById("paidby").innerHTML=txt+ "<div class='row' style='padding:2px'><div class='col-sm-4'><input type='number' placeholder="+str+"></div></div>";
But I want to know if there is any other better way using angularJS or javascript to do the same so that if I need to remove one or all of the textfields later on, it can be done easily. By removing means deleting and NOT hiding.
(becuase if I want to remove for example textfield 'two' now, I have no idea how I remove it)
You don't want to manipulate the DOM within your controller. Often times, there are better ways to do this within the framework that Angular provides.
You can do this by having another ng-repeat which loops over an array you declare within your controller. For example:
In your view:
<section id="paidby" ng-repeat="textfield in textfields">
<div class='row' style='padding:2px'>
<div class='col-sm-4'>
<input type='number' placeholder="{{textField.str}}" ng-model="textField.value">
</div>
</div>
</section>
In your controller, within your button ng-click logic:
// To add:
$scope.textFields.push({ str: someVariable, value: someValue });
// To remove:
var index = $scope.textFields.map(function(t) { return t.value; }).indexOf(someValue);
if (index !== -1) {
$scope.textFields.splice(index, 1);
}
Try hiding the inputs to start with, then show them if the appropriate button is clicked:
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<div ng-app="" ng-init="array=['one','two','three','four','five']; show=[false,false,false,false,false]">
<button ng-repeat="item in array" ng-click="show[$index] = !show[$index]">{{item}}</button>
<br>
<input type="text" ng-repeat="item in array" placeholder="{{item}}" ng-if="show[$index]" />
</div>

Dynamically add text box

Newbie at web..
This should be simple. I have text box the user should write City. I'd like the user to press on "Add City" and another text box will be shown (do this up to 3 times). can you give me headstart on how to implement this?
<section class="row-inner clearfix">
<section class="form-field">
#Html.TextBoxFor(m => m.Cities, new { #class = "autocomplete-init-no-img"})
<label>Cities</label>
</section>
<section class="form-field">
Add City
</section>
</section>
You will need to do this client side via JS. The examples I am showing you use JQuery.
Something like
$("#button").click(function(){
$("#section").append("<input type='text' name='City1'/>");
});
The problem with this is that you will end up dynamically having to deal with parameters. If you know you only want to have 3, then that is fine.
If you wanted to use more of the built in controls, you could do something like.
<div>#Html.TextBoxFor(...city1...)</div>
<div class="hidden">#Html.TextBoxFor(....city2....)</div>
Then for the JS, you could just find the first hidden one and unhide it.
$("#button").click(function(){
$(".hidden").first().show();
});
You will also want to hide the "add city" button after all the cities that can be added have been added.
Hope that helps.
Javascript to create textbox with properties...
var input = document.createElement('input');
input.type = "text";
//...
container.appendChild(input);
make a button and add an onClick function
<button id="myButton" onClick="javaScriptFunction();"> button Text </button>
in the function create the button (see code above) and add it to the HTML body ...

how to add multiple div within one div using angular.js

I am new to Anjular.js. I just started to learn today so I hope all you can help me.
I have html file like this:
<div ng-conrtoller="add">
<div >
<div>{{ username }}</div>
<div>
<input type="text" ng-model="name">
<button ng-click="addname">save</button>
</div>
In controller.js file :
app.controller("add",function($scope)
{
$scope.addname=function()
{
$scope.username=$scope.name;
}
});
When I click on save button after I enter text into text filed, the entered text will be displayed within one div. If I again do the same, the name will be replaced but I want to display previously entered text as well as any text entered in the future.
Thanks.
i want to display previously entered text as well as in future enter text
You can use array to store multiple items, push items to array and use ngRepeat
HTML
<div>
<div ng-repeat="username in usernames">{{ username }}</div>
<div>
<input type="text" ng-model="name">
<button ng-click="addname()">save</button>
JS
$scope.usernames = [] ;
$scope.addname=function() {
$scope.usernames.push($scope.name);
$scope.name = "";
}
Working Demo
Currently use only unique items for testing

Categories

Resources