Multiple elements to be called by a function - javascript

I have two radio buttons and a date picker and if I click or make changes to any of those three, all the values of the corresponding elements should be updated to an array. I've tried and failed.
Here is what I've created (jQuery):
if ($(["#submitDates"], ["input.usage"], ["input.scope"]).on("change")) {
var fromDate = $("#from_date").val();
var toDate = $("#to_date").val();
var usage = $('input.usage').val();
var scope = $('input.scope').val();
var data = {};
data.dateRange = `${fromDate}->${toDate}`;
data.scope = scope;
data.usage = usage;
console.clear();
console.log(data);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-2">
<input type="radio" class="usage" name="usages" value='email' checked> Email Usage
</div>
<div class="col-md-2">
<input type="radio" class="usage" name="usages" value='mail'> Mail Usage
</div>
<input type="radio" class="scope" name="scope" value="cm"> Current Month 
<input type="radio" class="scope" name="scope" value="q"> This Quarter 
<input type="radio" class="scope" name="scope" value="cy"> This Year 
<input type="text" class="form-control" id='from_date' name="start" placeholder="MM/DD/YYYY" />
<div class="input-group-append">
<span class="input-group-text bg-info b-0 text-white">TO</span>
</div>
<input type="text" class="form-control" id='to_date' name="end" placeholder="MM/DD/YYYY" /> 
<button class='btn btn-sm btn-success btn-circle' id="submitDates" style="border-radius: 50%"><i class='bi bi-check-lg' style='font-size: 16px;'></i></button>

There's quite a few issues in your code:
The selector in your jQuery object is wrong. Provide multiple selectors in a single comma delimited string, not multiple arguments containing strings in arrays.
Don't put a jQuery event handler in an if condition, it's useless
The change event handler syntax is wrong, you didn't provide the function argument which binds the handler to run when the event fires.
data is an object, not an array, as your title/question states
You need to read the val() from the selected .usage and .scope elements only.
  isn't a valid HTML character entitiy. I presume you mean instead, but even then this is redundant.
With those issues fixed, the code would look something like this:
let $fromDate = $("#from_date")
let $toDate = $("#to_date");
let $usage = $('input.usage');
let $scope = $('input.scope');
function handleFormUpdate() {
var data = {
dateRange: `${$fromDate.val()} -> ${$toDate.val()}`,
scope: $scope.filter(':checked').val(),
usage: $usage.filter(':checked').val()
};
console.log(data);
}
$('#submitDates').on('click', handleFormUpdate);
$('input.usage, input.scope').on("change", handleFormUpdate);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="col-md-2">
<input type="radio" class="usage" name="usages" value="email" checked> Email Usage
</div>
<div class="col-md-2">
<input type="radio" class="usage" name="usages" value="mail"> Mail Usage
</div>
<input type="radio" class="scope" name="scope" value="cm"> Current Month
<input type="radio" class="scope" name="scope" value="q"> This Quarter
<input type="radio" class="scope" name="scope" value="cy"> This Year
<input type="text" class="form-control" id="from_date" name="start" placeholder="MM/DD/YYYY" />
<div class="input-group-append">
<span class="input-group-text bg-info b-0 text-white">TO</span>
</div>
<input type="text" class="form-control" id="to_date" name="end" placeholder="MM/DD/YYYY" />
<button class='btn btn-sm btn-success btn-circle' id="submitDates" style="border-radius: 50%">
<i class='bi bi-check-lg' style='font-size: 16px;'></i>
Check
</button>

Related

How to disable a radio button if the other one is selected?

I'm trying to disable a radio button if the other one is selected.
Next to the radio input is a text input in which if they choose the option, they would write the age depending on the selection of the radio (months or years).
Ideally, the text input would be disabled too. I have this code right now but it's not working:
<div class="md-form mb-3">
<i class="fas fa-paw prefix grey-text"></i><label data-error="wrong" data-success="right" style="padding-left: 5px">Age: </label>
<br />
<input type="radio" id="age_in_years" name="age_in_years" value="years">
<label for="age_in_years">Años:</label><input id="age_in_years"type="number" name="age_in_years" ng-model="age_in_years" class="form-control" style="margin-left: 5px;width: 70px;"/>
<input type="radio" id="age_in_months" name="age_in_months" value="months">
<label for="age_in_months">Months:</label><input id="age_in_months" type="number" name="age_in_months" value="age_in_months" ng-model="age_in_months" class="form-control" style="margin-left: 5px;width:70px;"/>
</div>
<script>
function selection() {
let x = document.getElementById("age_in_years");
let y = document.getElementById("age_in_months");
if (x.checked()) {
document.getElementById("age_in_months").disabled = true;
}
else if (y.checked()) {
document.getElementById("age_in_years").disabled = true;
}
}
</script>
I would refactor the HTML slightly and generate the radio buttons with the same name so that only 1 can ever be checked at a time. With that in place some simple javascript to determine the other inputs can be used to disable the number input.
label elements should not be used for arbitrary HTML - they are to be associated with input elements ( either using for=ID syntax or by wrapping the input element itself ) - hence some alterations to the markup.
document.addEventListener('change',e=>{
if( e.target.name=='age_unit' ){
let parent=e.target.parentNode;
let self=parent.querySelector(`input[type='number'][name='age[${e.target.value}]']`);
let other=parent.querySelector(`input[type='number']:not( [name='age[${e.target.value}]'] )`);
self.disabled=false;
other.disabled=true;
self.required=true;
other.required=false;
self.focus();
}
})
[type='number']{
width:70px;
}
<div class="md-form mb-3">
<i class="fas fa-paw prefix grey-text"></i>
<h2>Age:</h2>
<input type="radio" name="age_unit" value="years" />
<label>Años:
<input type="number" name="age[years]" ng-model="age_in_years" class="form-control" disabled />
</label>
<input type="radio" name="age_unit" value="months" />
<label>Months:
<input type="number" name="age[months]" ng-model="age_in_months" class="form-control" disabled />
</label>
</div>
A radio type is grouped by the name, so using the same name would already give the behavior you want, without needing any JavaScript.
<div class="md-form mb-3">
<i class="fas fa-paw prefix grey-text"></i>
<label data-error="wrong" data-success="right" style="padding-left: 5px">Age: </label>
<br>
<input type="radio" id="age_in_years" name="age" value="years">
<label for="age_in_years">Años:</label><input id="age_in_years"type="number" name="age_in_years" ng-model="age_in_years" class="form-control" style="margin-left: 5px;width: 70px;"/>
<input type="radio" id="age_in_months" name="age" value="months">
<label for="age_in_months">Months:</label>
<input id="age_in_months" type="number" name="age_in_months" value="age_in_months" ng-model="age_in_months" class="form-control" style="margin-left: 5px;width:70px;"/>
</div>
This would make sure that if one of radio elements is clicked or, once another one is clicked, the previous would be unchecked.
Because you have a value there, there's no reason to use different names, because the value already hints what kind of data has been submitted or is required.

How to check multiple selectors to trigger an event?

New to jquery but I am working on a responsive calendar. Now I have a start date and an end date field. If the end date is populated, the reoccurrence check box shows as it removes it from the not-visible class.
How can I add a check on the start date also? I want the check box to show when both of the start and end fields are filled not just one.
$("#end_date").on("input", function (){
if($('#end_date').length >= 1) {
$("#reoccurrence").removeClass('not-visible');
} else {
$("#reoccurrence").addClass('not-visible');
}
});
.not-visible {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col">
<div class="md-form md-form-container-fix">
<input type="text" id="start_date" class="form-control date-picker" name="start_date" required />
<label for="start_date">Start Date</label>
</div>
</div>
<div class="col">
<div class="md-form md-form-container-fix">
<input type="text" id="end_date" class="form-control date-picker" name="end_date" required />
<label for="end_date">End Date</label>
</div>
</div>
<div class="form-check not-visible" id="reoccurrence" name="reoccurrence">
<input class="form-check-input" type="checkbox" id="is_reoccurring" name="is_reoccurring" value="1" />
<label class="form-check-label" for="is_reoccurring"> Reoccurrence? </label>
</div>
In this context, using length will tell you whether that input exists in the DOM (0 = doesn't exist, 1 = exists), but it won't evaluate the values of the inputs.
length
The number of elements in the jQuery object.
The number of elements currently matched.
Instead, I recommend using val() to verify that the values of both inputs are not empty strings.
In the demonstration below, I define each input and the "reoccurrence" element as variables. I use add() to combine the two inputs and bind the event handler to both. Alternatively, you could simply select both inputs: $("#start_date,#end_date"); see multiple selector.
Upon input, I define a boolean "oneEmpty" variable based on the values of both inputs. Then, I use toggleClass() to "add or remove one or more classes ... depending on ... the value of the state argument."
When either input is empty, the "oneEmpty" state is true and the "not-visible" class is toggled on. When both inputs are filled, the state is false and the class is toggled off.
var $start_date = $('#start_date');
var $end_date = $('#end_date');
var $reoccurrence = $("#reoccurrence");
$start_date.add($end_date).on("input", function() {
let oneEmpty = $start_date.val() == '' || $end_date.val() == '';
$reoccurrence.toggleClass('not-visible', oneEmpty);
});
.not-visible {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col">
<div class="md-form md-form-container-fix">
<input type="text" id="start_date" class="form-control date-picker" name="start_date" required />
<label for="start_date">Start Date</label>
</div>
</div>
<div class="col">
<div class="md-form md-form-container-fix">
<input type="text" id="end_date" class="form-control date-picker" name="end_date" required />
<label for="end_date">End Date</label>
</div>
</div>
<div class="form-check not-visible" id="reoccurrence" name="reoccurrence">
<input class="form-check-input" type="checkbox" id="is_reoccurring" name="is_reoccurring" value="1" />
<label class="form-check-label" for="is_reoccurring"> Reoccurrence? </label>
</div>

How to get data from a form which is written in inner HTML?

This is my code, here I want to access data from the textfields, how can I access them
This is my javascript function to add new form eevrytime add button is clicked
function elementAppender() {
if (count <= 5) {
let element = document.createElement('div');
element.id = `${count}`
Here, the code from which I have to get data is written in inner html
element.innerHTML = `<div class="col-md-6 mx-auto my-5" id="myDiv">
<div class="kumite-form">
<button type="button" class="close col-md-2" data-dismiss="form" style="color: coral; float: right;" onclick="remdiv(), count-=1">×</button>
<form action="#" class="mx-auto">
<h3 style="text-align: left;margin-left:10%">Group ${count}</h3>
<ul>
<li>
<div class="text-center">
Category:
<input class="" type="radio" name="category" value="female" style="font-size: 0.5px;">
<label>Male</label>
<input class="" type="radio" name="category" value="male" style="font-size: 0.5px;">
<label>Female</label>
</div>
</li>
<h4 style="text-align: left;margin-left:10%">Player 1</h4>
<li><input type="text" placeholder="Player 1 Name"></li>
<input type="text" placeholder="Date of Birth" onfocus="(this.type='date')"
onblur="(this.type='text')">
<li><input type="Number" placeholder="Weight (in kg)"></li>
The "value" property in JS comes in handy.
var myInput = document.querySelector("#idOfField").value

Storing HTML Form input as an Object using a Constructor class and a dynamic variable name (Plain JS)

<form id="projectForm" onsubmit="return ptitle.value = new Project(this);">
<div class="form-row">
<label for="ptitle">Title: </label>
<input type="text" id="ptitle" name="ptitle"><br>
</div>
<div class="form-row">
<label for="pdescription">Discription: </label>
<input type="text" id="pdescription" name="pdescription"><br>
</div>
<div class="form-row">
<label for="pdueDate">Due Date</label>
<input type="date" id="pdueDate" name="pdueDate"><br>
</div>
<div class="form-row">
<label for="high">High</label>
<input type="radio" id="high" name="priority">
<label for="low">Low</label>
<input type="radio" id="low" name="priority"><br>
<input id="submit" type="submit" value="submit">
</div>
</form>
So I would like to take the data submitted from this form and call a constructor method within the Projects class. I'd also like to be able to dynamically generate the variable name from the title value of the form. Here's the JavaScript code. I'll need to use plain JS as that is what's required for the project! We're also required to use a constuctor class or factory function to generate the projects. As you can see I've tried to take a stab at it but unfortunately it hasn't worked. Thanks in advance.
class Project {
constructor(form) {
this.title = form.ptitle.value;
this.description = form.pdescription.value;
this.dueDate = form.pdueDate.value;
this.priority = form.priority.value;
}
todoList = {};
addTodoList(value, description) {
this.todoList[value] = description;
}
removeTodoList(key) {
delete this.todoList[key];
}
}
Thanks again!!!
I'd also like to be able to dynamically generate the variable name from the title value of the form That sounds like a terrible idea...
Well here you go
class Project {
constructor(form) {
this.title = form.ptitle.value;
this.description = form.pdescription.value;
this.dueDate = form.pdueDate.value;
this.priority = form.priority.value;
}
todoList = {};
addTodoList(value, description) {
this.todoList[value] = description;
}
removeTodoList(key) {
delete this.todoList[key];
}
}
<form id="projectForm" onsubmit="window[ptitle.value] = new Project(this);return false">
<div class="form-row">
<label for="ptitle">Title: </label>
<input type="text" id="ptitle" name="ptitle"><br>
</div>
<div class="form-row">
<label for="pdescription">Discription: </label>
<input type="text" id="pdescription" name="pdescription"><br>
</div>
<div class="form-row">
<label for="pdueDate">Due Date</label>
<input type="date" id="pdueDate" name="pdueDate"><br>
</div>
<div class="form-row">
<label for="high">High</label>
<input type="radio" id="high" name="priority">
<label for="low">Low</label>
<input type="radio" id="low" name="priority"><br>
<input id="submit" type="submit" value="submit">
</div>
</form>

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.

Categories