How can i check radio button by default? - javascript

On page load i want to show below radio button selected by default i used html attribute but its not working. So on page load I want to show all process radio button checked by default. Is there any other way to achieve this task?
radio.html
<div class="panel panel-default">
<div class="panel-heading">View/Search Inventory</div>
<div class="panel-body">
<div class="row">
<div class="col-md-2">
<select kendo-drop-down-list k-data-text-field="'name'"
k-data-value-field="'value'" k-data-source="filterOptions"
k-ng-model="kfilter" ng-model="filter" ng-change="onChange()"></select>
</div>
<div ng-show="filter=='PROCESS'" ng-init="search.showCriteria='allProcess';onChange()">
<div class="col-md-7">
<label class="radio-inline" for="allProcess"> <input
type="radio" name="optionsRadios1" ng-value="'allProcess'"
id="allProcess" ng-model="search.showCriteria"
ng-change="selectSearchType()"> Show All Processes
</label> <label class="radio-inline" for="ratedProcess"> <input
type="radio" name="optionsRadios1" ng-value="'ratedProcess'"
id="ratedProcess" ng-model="search.showCriteria"
ng-change="selectSearchType()"> Show Rated Processes
</label> <label class="radio-inline" for="unratedProcess"> <input
type="radio" name="optionsRadios1" ng-value="'unratedProcess'"
id="unratedProcess" ng-model="search.showCriteria"
ng-change="selectSearchType()"> Show Unrated Processes
</label>
</div>
</div>
<div ng-show="filter=='RISK'">
<div class="col-md-7">
<label class="radio-inline" for="allRisk"> <input
type="radio" name="optionsRadios1" ng-value="'allRisk'"
id="allRisk" ng-model="search.showCriteria" ng-checked="true"
ng-change="selectSearchType()"> Show All Risks
</label> <label class="radio-inline"> <input type="radio"
name="optionsRadios1" ng-value="'unalignedRisk'"
ng-model="search.showCriteria" ng-change="selectSearchType()">
Show Unaligned Risks
</label>
</div>
</div>
<div ng-show="filter=='CONTROL'">
<div class="col-md-7">
<label class="radio-inline" for="allControl"> <input
type="radio" name="optionsRadios1" ng-value="'allControl'"
id="allControl" ng-model="search.showCriteria" ng-checked="true"
ng-change="selectSearchType()"> Show All Controls
</label> <label class="radio-inline" for="unalignedControl"> <input
type="radio" name="optionsRadios1" ng-value="'unalignedControl'"
id="unalignedControl" ng-model="search.showCriteria"
ng-change="selectSearchType()"> Show Unaligned Controls
</label>
</div>
</div>
<div class="col-md-2">
<button class="btn btn-default" type="button" ng-click="search(0)">
<span class="glyphicon glyphicon-search"></span> Search
</button>
</div>
</div>
<div class="row">
<!--<label for="filterBy" class="col-md-1">Filter by: </label>
<div class="col-md-3">
<select kendo-drop-down-list k-data-text-field="'name'" k-option-label="'Select'"
k-data-value-field="'value'" k-data-source="filterByOptions"
k-ng-model="kfilterBy" ng-model="filterBy" style="width: 100%"></select>
</div>
<div class="col-md-3">
<select kendo-drop-down-list k-data-text-field="'name'"
k-data-value-field="'value'" k-data-source="filterByValues" k-option-label="'Select'"
k-ng-model="kfilterByValue" ng-model="filterByValue" style="width: 100%"></select>
</div> -->
<div class="col-md-3">
<a href="" ng-show="!showAdvance" ng-click="advanceFilter()">Advanced
Search</a> <a href="" ng-show="showAdvance" ng-click="advanceFilter()">Basic
Search</a>
<!-- <button ng-show="!showAdvance" class="btn btn-default" type="button" ng-click="search()">Go</button> -->
</div>
</div>
<form role="form" name="formTimeLine" kendo-validator="validator"
k-options="myValidatorOptions">
<div ng-show="showAdvance">
<div class="clone" ng-repeat="input in inputs">
<br />
<div class="row">
<div class="col-md-1">
<a ng-if="inputs.length < searchOptions.length"
class="add col-md-1" name="addnumadd" ng-click="add($index)"> </a>
<a ng-if="inputs.length >1" class="delete col-md-1"
name="deletenumadd" ng-click="remove($index)"> </a>
</div>
<div class="col-md-3">
<select kendo-drop-down-list k-data-text-field="'name'"
k-option-label="'Select'" k-data-value-field="'value'"
k-data-source="searchOptions" name="searchBy-{{$index}}"
ng-model="input.searchBy"
data-required-msg="Please select the value"
ng-change="clearPreviousValue({{$index}})" data-duplicate=""
style="width: 100%" required></select>
</div>
<div class="col-md-3">
<input type="text" class="form-control"
ng-model="input.searchValue" placeholder="Enter search item"
ng-maxlength="256" name={{$index}}>
</div>
<div class="col-md-4">
<input type="radio" name={{$index}} value="exactMatch"
ng-model="input.exactMatch" data-requiredCheckbox=""> Exact
Match <input type="radio" name={{$index}} value="contains"
ng-model="input.exactMatch" data-requiredCheckbox=""> Contains
<span class="k-invalid-msg" data-for={{$index}}></span>
</div>
</div>
</div>
</div>
</form>
</div>
<div id="outergrid" class="row">
<ng-include src="gridInclude"></ng-include>
</div>
</div>
radio.js
$scope.processSearchOptions = processSearchOptions;
$scope.riskSearchOptions = riskSearchOptions;
$scope.controlSearchOptions = controlSearchOptions;
$scope.filterByOptions = filterByOptions;
$scope.filterByValues = filterByValues;
$scope.searchOptions = processSearchOptions;
$scope.onChange = function () {
var value = $scope.filter;
$scope.postArgs.page = 1;
if (value === 'PROCESS') {
$scope.search.showCriteria = 'allProcess';
$scope.searchOptions = processSearchOptions;
$scope.gridInclude = 'views/viewAll/processGrid.html';
}
if (value === 'RISK') {
$scope.search.showCriteria = 'allRisk';
$scope.searchOptions = riskSearchOptions;
$scope.gridInclude = 'views/viewAll/riskGrid.html';
}
if (value === 'CONTROL') {
$scope.search.showCriteria = 'allControl';
$scope.searchOptions = controlSearchOptions;
$scope.gridInclude = 'views/viewAll/controlGrid.html';
}
$scope.showAdvance = false;
$scope.clearAdvFilter();
$scope.postArgs = {
page: 1
};
};
//initialize process grid
initializeGrid('process');
$scope.processGridOptions = getProcessGridOptions($scope.postArgs, gridColumns.processGridColumns);
$scope.processInnerGridOptions = viewSearchInvService.getInnerProcessGrid;
//initialize risk grid
initializeGrid('risk');
$scope.riskGridOptions = getProcessGridOptions($scope.postArgs, gridColumns.riskGridColumns);
$scope.riskInnerGridOptions = viewSearchInvService.getInnerRiskGrid;
//initialize control grid
initializeGrid('control');
$scope.controlGridOptions = getProcessGridOptions($scope.postArgs, gridColumns.controlGridColumns);
$scope.controlInnerGridOptions = viewSearchInvService.getInnerControlGrid;
$scope.ProcessEditHandler = function (id) {
ViewEditPrcsService.saveProcessId(id);
};
$scope.RiskEditHandler = function (id) {
ViewEditRiskService.saveRiskId(id);
};
$scope.advanceFilter = function () {
if ($scope.showAdvance) {
$scope.clearAdvFilter();
$scope.showAdvance = false;
} else {
$scope.showAdvance = true;
}
};
$scope.clearAdvFilter = function () {
$scope.inputs = [];
$scope.inputs.push(getNewObject());
};
$scope.search = function () {
if ($scope.validator.validate() || !$scope.showAdvance) {
searchCriteria(1);
searchFlag = true;
if ($scope.filter === 'PROCESS') {
$scope.search.process.dataSource.read();
}
if ($scope.filter === 'RISK') {
$scope.search.risk.dataSource.read();
}
if ($scope.filter === 'CONTROL') {
$scope.search.control.dataSource.read();
}
}
};
$scope.selectSearchType = function () {
$scope.clearAdvFilter();
$scope.showAdvance = false;
$scope.search();
};
$scope.add = function () {
$scope.inputs.push(getNewObject());
};
$scope.remove = function (index) {
$scope.inputs.splice(index, 1);
};
$scope.myValidatorOptions = {
rules: {
duplicate: function (input) {
return checkDuplicates(input.val(), input[0].name);
},
requiredCheckbox: function (input) {
return !(input[0].type === 'radio' && !$scope.inputs[input[0].name].exactMatch && !$scope.inputs[input[0].name].contains);
}
},
messages: {
duplicate: 'Option already selected. please select another option',
requiredCheckbox: 'Operator is required'
}
};
$scope.clearPreviousValue = function (index) {
$scope.inputs[index].searchValue = '';
};
});

Without knowing more about the specifics of when you want this checked, apply the following using ngChecked. In this case, checked if true, but this can be any expression
ng-checked="true"
JSFiddle Link
In response to your updated code, you could leverage ngInit on your parent <div> for defaulting one radio button in a group. Note for isolating the direct issue I have slimmed down most of this markup
<div ng-init="search.showCriteria='allProcess'">
Updated JSFiddle Link

You need to make sure your model is set to the value of the radio box.
$scope.search.showCriteria = 'allProcess'
As a side node, you don't need to be using ng-value here. You could use just use value="allProcess" because ng-value is only needed for Angular expressions, not plain strings.

Related

All the Javascript functions for my web page suddenly stopped being recognized

All of the buttons on my web site suddenly stopped working. When I try to press them, in the console it says that they don't exist. I've checked to make sure the Javascript filename in the script tag is correct. I made a folder only for my current Javascript, html, and CSS files. I tried changing the script tag from being at the end of the html document to in the header. None of these things did anything.
medAppFreshStart3.html:33 Uncaught TypeError: noteModal is not a function
at HTMLButtonElement.onclick (medAppFreshStart3.html:33)
onclick # medAppFreshStart3.html:33
<!DOCTYPE html>
<html>
<header>
<script src="medAppFreshStart3.js"></script>
<link rel="stylesheet" href="medAppStyle3.css" />
</header>
<body>
<div class="container">
<div class="d1">
demographics
<button onclick="newPatient()" id="newPatient">+ New Patient</button>
<button onclick="localStorage.clear()" id="clearPtData">
Clear Patient Data</button
><br />
<!--<label for="search">Patient Search</label>-->
<input id="search" placeholder="Enter patient name" />
<button id="searchButton">search</button>
<p id="nameDisplay"></p>
<p id="ageDisplay"></p>
<!--<label for="search">patient search</label>
<input
type="search"
onsearch="findPatient()"
name="search"
id="search"
/>-->
</div>
<div class="d2 flex-container">
current note
<button onclick="noteModal()" id="newNote">+ Add</button>
<div class="content">
<div class="current-note-sub content-1" id="subjective">
Subjective:
</div>
<div class="current-note-sub content-1" id="objective">
Objective:
</div>
<div class="current-note-sub content-1" id="assessment">
Assessment:
</div>
<div class="current-note-sub content-1" id="plan">Plan</div>
</div>
</div>
<div class="d3">
Problem-list
<button onclick="addProblem()" id="new problem">+ Add</button>
<div class="content">
<div class="problem">Problem:</div>
<div class="problem">Problem:</div>
<div class="problem">Problem:</div>
<div class="problem">PRoblem:</div>
</div>
</div>
<div class="d4 flex-container">
prescriptions
<button onclick="addPrescription()" id="new prescription">+ Add</button>
<div class="content" id="prescriptions">
<div class="prescription" id="prescription1">prescription1</div>
<div class="prescription" id="prescription2">prescription2</div>
<div class="prescription" id="prescription3">prescription3</div>
<div class="prescription" id="prescription4">prescription3</div>
</div>
</div>
<div class="d5 flex-container">
Previous Notes
<div class="content">
<div class="past-note" id="past-note1">Date: Complaint:</div>
<div class="past-note" id="past-note2">Date: Complaint:</div>
<div class="past-note" id="past-note3">Date: Complaint:</div>
<div class="past-note" id="past-note4">Date: Complaint:</div>
</div>
</div>
</div>
<div id="addPrescription" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span onclick="closePrescription()" class="close">×</span>
<form action="" method="post" id="prescriptionForm">
<label for="Drug"> Drug:</label>
<input
type="text"
id="Drug"
name="Drug"
type="text"
reqired
aria-required="true"
/>
<label for="Dosage"> Dosage:</label>
<input
type="number"
id="Dosage"
name="Dosage"
required
aria-required="true"
/>
<label for="measurement">Measurement</label>
<select id="measurement" name="measurement">
<option value="micrograms">micrograms</option>
<option value="milligrams">milligrams</option>
<option value="grams">grams</option>
</select>
</form>
<button
type="submit"
value="submit"
form="PrescriptionForm"
onclick="createPrescription(); closePrescription()"
>
+ Create
</button>
</div>
</div>
<div id="noteModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span onclick="closeNote()" class="close">×</span>
<form action="" method="post" id="noteForm" name="noteform">
<label for="Date"> Date: </label>
<input
type="text"
id="Date"
name="Date"
reqired
aria-required="true"
/>
<label for="complaint"> Complaint: </label>
<input
type="text"
id="complaint"
name="complaint"
reqired
aria-required="true"
/>
<label for="subjective">Subjective</label>
<textarea id="subjective" name="subjective"></textarea>
<label for="objective">Objective</label>
<textarea id="objective" name="objective"></textarea>
<label for="assessment">Assessment</label>
<textarea id="assesment" name="assessment"></textarea>
<label for="plan">Plan</label>
<textarea id="plan" name="plan"></textarea>
</form>
<button onclick="createNote(), closeNote()">+ Create</button>
</div>
</div>
<div id="addProblem" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span onclick="closeProblem()" class="close">×</span>
<form action="" method="post" id="problemForm">
<label for="problem"> Problem:</label>
<input
type="text"
id="problemForm"
name="problemForm"
reqired
aria-required="true"
/>
</form>
<button
type="submit"
value="submit"
form="problem"
onclick="closeProblem()"
>
+ Create
</button>
</div>
</div>
<div id="newPtDemographics" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span onclick="closeDemo()" class="close">×</span>
<form action="" method="post" id="demoForm">
<label for="name"> Name:</label>
<input
type="text"
id="name"
name="name"
reqired
aria-required="true"
/>
<label for="age"> Age:</label>
<input
type="number"
id="age"
name="age"
reqired
aria-required="true"
/>
</form>
<button onclick="createPatient(), closeDemo()">+ Create</button>
</div>
</div>
</body>
</html>
```
```function newPatient() {
const addPatient = document.getElementById('newPtDemographics');
addPatient.style.display = 'block';
}
function findPatient() {
let name = document.getElementById(search);
name = name.innerText;
console.log(name);
}
const button1 = document.getElementById('searchButton');
searchButton.addEventListener('click', () => {
const name = document.getElementById('search').value;
//console.log(name);
let patients = localStorage.getItem('patients');
patients = JSON.parse(patients);
let patient = patients[name];
nameDisplay = document.getElementById('nameDisplay');
ageDisplay = document.getElementById('ageDisplay');
nameDisplay.innerHTML = 'Name: ' + patient[key];
ageDisplay.innerHTML = 'Age' = patient.age;
//console.log(patient);
//patients = JSON.parse(patients);
});
function createPatient() {
let patients = localStorage.getItem('patients');
const name = document.getElementById('name').value;
const age = document.getElementById('age').value;
if (patients !== null) {
//instead of parsing here can just append array with new patient if it already exists.
//Will need to parse to retrieve data to fill patient details when select new patient or
//reopen broswer.
patients = JSON.parse(patients);
} else {
patients = {};
}
patients[name] = { age: age };
//patients.push({ [name]: { age: age } });
localStorage.setItem('patients', JSON.stringify(patients));
//console.log(patients[name]);
}
function addPrescription() {
const addPrescription = document.getElementById('addPrescription');
addPrescription.style.display = 'block';
}
function createPrescription() {
const div = document.getElementById('prescriptions');
const newPrescription = document.createElement('div');
newPrescription.classList.add('prescription');
const name = document.getElementById('name').value;
console.log(name);
//var patient = JSON.parse(localStorage.getItem('patients.[name]'));
//newPrescription.innerHTML = patient;
//div.appendChild(newPrescription);
//console.log('testing');
//console.log(patient);
//console.log('testing');
/*
newPrescription.innerHTML =
'Drug: ' +
document.getElementById('prescriptionForm').Drug.value +
' Dosage: ' +
document.getElementById('prescriptionForm').Dosage.value +
' ' +
document.getElementById('prescriptionForm').measurement.value;
div.appendChild(newPrescription);
*/
}
function createNote() {
let noteForm = document.getElementById('noteForm');
let formData = new FormData(noteForm);
var object = {};
formData.forEach(function (value, key) {
object[key] = value;
});
var note = JSON.stringify(object);
}
function noteModal() {
const noteModal = document.getElementById('noteModal');
noteModal.style.display = 'block';
}
function addProblem() {
const addProblem = document.getElementById('addProblem');
addProblem.style.display = 'block';
}
function closeProblem() {
const addProblem = document.getElementById('addProblem');
addProblem.style.display = 'none';
}
function closeNote() {
const noteModal = document.getElementById('noteModal');
noteModal.style.display = 'none';
}
function closePrescription() {
const addPrescription = document.getElementById('addPrescription');
addPrescription.style.display = 'none';
}
function closeDemo() {
const addPatient = document.getElementById('newPtDemographics');
addPatient.style.display = 'none';
}

Change variables on click after AJAX call

I can't find an answer or solution to this issue that I'm facing. So I have made a script (php & jquery) that allows users to promote their "listings" on my website. So when they land on a page they can select which listing they want to promote, then when they select it the jquery calls AJAX (on select change) which then calls the php page and get the plans for the selected listing. Since I'm using PayPal Standard I can only pass variables with one input (I'm storing all variables in one custom input and then read them on the php page as array). Everything works fine, my listing ID gets changed when the listing is changed, the days duration gets changed when they change it in input but the thing that doesn't work is checkboxes.
So in the datebase I have three columns under listing table (featured, topsearch, sidebar) and by default their value is 0. So on the page I disable all plans that are already promoted with getting the value out of the datebase and then if the value is 0 the plan is available for promoting, and if its 1 its already promoted and its disabled for promoting. Now when the checkbox is selected for the certain plan it changes the checkbox value to 1, and then the plan is to update the listing and for example if user selected sidebar it will update the column from 0 to 1. But whatever I do the var featured, var topsearch and var sidebar won't change in my AJAX call after clicking them. It updates the checkbox input value but it won't reflect in my AJAX call.
jQuery:
$('.select-placement').hide();
$('.s-b').hide();
$('#count-duration').text('0');
$("#pick_listing, #no-text, #customCheck1, #customCheck2, #customCheck3").change(function() {
var selectedValue = $('#pick_listing').val();
$.ajax({
url: '../paypal/promote/promote.php',
type: 'POST',
data: {selectedValue: selectedValue},
success: function(data) {
$('.select-placement').show();
$(".select-results").html(data);
$('.s-b').show();
let ajax_duration = parseFloat($('#no-text').val() || '0');
if (ajax_duration == 1) {
$('#count-duration').text(ajax_duration + " day");
} else {
$('#count-duration').text(ajax_duration + " days");
}
// Changes checkbox value if its checked -- NOT WORKING
if ($('#customCheck1').is(':checked')) {
$("#customCheck1").val("1");
} else {
$("#customCheck1").val("0");
}
if ($('#customCheck2').is(':checked')) {
$("#customCheck2").val("1");
} else {
$("#customCheck2").val("0");
}
if ($('#customCheck3').is(':checked')) {
$("#customCheck3").val("1");
} else {
$("#customCheck3").val("0");
}
var duration_value = $('#no-text').val();
var listing = $('#pick_listing').val();
var featured = $('#customCheck1').val(); // It should update when the checkbox is checked
var topsearch = $('#customCheck2').val(); // It should update when the checkbox is checked
var sidebar = $('#customCheck3').val(); // It should update when the checkbox is checked
// This is the custom PayPal input in which I store all the collected variables
// All variables changes on change function instead of checkbox
$('input[name=custom]').val("<?php echo $current_token; ?>," + listing + "," + duration_value + "," + featured + "," + topsearch + "," + sidebar);
$('#tots').text("0");
$('#tots2').text("0");
$('#icon1').css('color','#ccc');
$('#icon2').css('color','#ccc');
$('#icon3').css('color','#ccc');
}
});
});
promote.php file:
$placement_token = $_POST['selectedValue']; // Getting the value from AJAX
// Call the promote options
$listing_placement = mysqli_query($conn, "SELECT featured, topsearch, sidebar FROM listing WHERE listing_token='$placement_token'"); ?>
<form id="custom-form" class="row row-placement">
<?php while($place_row = mysqli_fetch_row($listing_placement)) {
if ($place_row[0] == 1) { ?>
<div class="col-sm-4 listing-disabled">
<div class="select-ad disabled-ad">
<div class="already-promoted">Already Promoted</div>
<div class="ad-image">
<div class="lp-select-top input-group margin-right-0 clearfix">
<div class="custom-control custom-checkbox cst-check">
<input type="checkbox" class="custom-control-input checks" id="customCheck1" data-price="10" value="1">
<label class="custom-control-label" for="customCheck1"></label>
</div>
</div>
<img src="https://classic.listingprowp.com/wp-content/themes/listingpro/assets/images/spotlight.png">
</div>
<div class="price-content">
<h5>Featured</h5>
<label for="customCheck1">$10 / day</label>
</div>
</div>
</div>
<?php } else { ?>
<div class="col-sm-4">
<div class="select-ad active-ad">
<div class="ad-image">
<div class="lp-select-top input-group margin-right-0 clearfix">
<div class="custom-control custom-checkbox cst-check">
<input type="checkbox" class="custom-control-input checks" id="customCheck1" data-price="10" value="0">
<label class="custom-control-label" for="customCheck1"></label>
</div>
</div>
<img src="https://classic.listingprowp.com/wp-content/themes/listingpro/assets/images/spotlight.png">
</div>
<div class="price-content">
<h5>Featured</h5>
<label for="customCheck1">$10 / day</label>
</div>
</div>
</div>
<?php } if ($place_row[1] == 1) { ?>
<div class="col-sm-4 listing-disabled">
<div class="select-ad disabled-ad">
<div class="already-promoted">Already Promoted</div>
<div class="ad-image">
<div class="lp-select-top input-group margin-right-0 clearfix">
<div class="custom-control custom-checkbox cst-check">
<input type="checkbox" class="custom-control-input checks" id="customCheck2" data-price="50" value="1">
<label class="custom-control-label" for="customCheck2"></label>
</div>
</div>
<img src="https://classic.listingprowp.com/wp-content/themes/listingpro/assets/images/topofsearch.png">
</div>
<div class="price-content">
<h5>Top of Search</h5>
<label for="customCheck2">$50 / day</label>
</div>
</div>
</div>
<?php } else { ?>
<div class="col-sm-4">
<div class="select-ad active-ad">
<div class="ad-image">
<div class="lp-select-top input-group margin-right-0 clearfix">
<div class="custom-control custom-checkbox cst-check">
<input type="checkbox" class="custom-control-input checks" id="customCheck2" data-price="50" value="0">
<label class="custom-control-label" for="customCheck2"></label>
</div>
</div>
<img src="https://classic.listingprowp.com/wp-content/themes/listingpro/assets/images/topofsearch.png">
</div>
<div class="price-content">
<h5>Top of Search</h5>
<label for="customCheck2">$50 / day</label>
</div>
</div>
</div>
<?php } if ($place_row[2] == 1) { ?>
<div class="col-sm-4 listing-disabled">
<div class="select-ad disabled-ad">
<div class="already-promoted">Already Promoted</div>
<div class="ad-image">
<div class="lp-select-top input-group margin-right-0 clearfix">
<div class="custom-control custom-checkbox cst-check">
<input type="checkbox" class="custom-control-input checks" id="customCheck3" data-price="20" value="1">
<label class="custom-control-label" for="customCheck3"></label>
</div>
</div>
<img src="https://classic.listingprowp.com/wp-content/themes/listingpro/assets/images/listingsidebar.png">
</div>
<div class="price-content">
<h5>Sidebar</h5>
<label for="customCheck3">$20 / day</label>
</div>
</div>
</div>
<?php } else { ?>
<div class="col-sm-4">
<div class="select-ad active-ad">
<div class="ad-image">
<div class="lp-select-top input-group margin-right-0 clearfix">
<div class="custom-control custom-checkbox cst-check">
<input type="checkbox" class="custom-control-input checks" id="customCheck3" data-price="20" value="0">
<label class="custom-control-label" for="customCheck3"></label>
</div>
</div>
<img src="https://classic.listingprowp.com/wp-content/themes/listingpro/assets/images/listingsidebar.png">
</div>
<div class="price-content">
<h5>Sidebar</h5>
<label for="customCheck3">$20 / day</label>
</div>
</div>
</div>
<?php } } ?>
</form>
And I really got confused because the var duration_value and var selectedValue gets updated on every change, but checkboxese won't. I have read that I should be using document on change instead of just change function but I tried and it didn't helped. I know that the posted question is messy but I couldn't replicate it in jsfiddle, sorry. I just need solutions on what could it be that is holding checkboxes to change its value on CHANGE.
Regards
Checkboxes are handled differently in html and in Javascript/JQuery. Value is not what you want to change here. You want to set your variable's value based on a checkbox property.
Based on your feedback I have updated the code where the select change makes the ajax call to initiate the form based on selected value. And then on change of any input in the form the values are read back to format the string for hidden field.
$('.select-placement').hide();
$('.s-b').hide();
$('#count-duration').text('0');
$("#pick_listing").change(function() {
var selectedValue = $('#pick_listing').val();
$.ajax({
url: '../paypal/promote/promote.php',
type: 'POST',
data: {selectedValue: selectedValue},
success: function(data) {
$('.select-placement').show();
$(".select-results").html(data);
$('.s-b').show();
$('#tots').text("0");
$('#tots2').text("0");
$('#icon1').css('color','#ccc');
$('#icon2').css('color','#ccc');
$('#icon3').css('color','#ccc');
}
});
});
$("#no-text, #customCheck1, #customCheck2, #customCheck3").change(function() {
let ajax_duration = parseFloat($('#no-text').val() || '0');
if (ajax_duration == 1) {
$('#count-duration').text(ajax_duration + " day");
} else {
$('#count-duration').text(ajax_duration + " days");
}
var duration_value = $('#no-text').val();
var listing = $('#pick_listing').val();
var featured = ($('#customCheck1').prop('checked')) ? "1" : "0";
var topsearch = ($('#customCheck2').prop('checked')) ? "1" : "0";
var sidebar = ($('#customCheck3').prop('checked')) ? "1" : "0";
// This is the custom PayPal input in which I store all the collected variables
// All variables changes on change function instead of checkbox
$('input[name=custom]').val("<?php echo $current_token; ?>," + listing + "," + duration_value + "," + featured + "," + topsearch + "," + sidebar);
});

Hidden input not submitted after updating value in on submit event

Using Laravel framework.
I don't get it. I have a hidden input with id = prime near the top.
<form name="paymentForm" action="/parking_302/upload_payment" method="POST" role="form" class="form-horizontal">
{{ csrf_field() }}
<input type="hidden" id="parking_lot_id" name="parking_lot_id" value="{{ $parking_lot_id }}">
<input type="hidden" id="booking_id" name="booking_id" value="{{ $booking_id }}">
<input type="hidden" id="Price" name="Price" value="{{ $Price }}">
<input type="hidden" id="prime" name="prime"> {{-- To be obtained --}}
<legend>電子發票 & TapPay 付款</legend>
<div class="form-group">
<label for="CustomerEmail" class="col-lg-3 col-md-3 col-xs-4">電子信箱</label>
<div class="col-lg-9 col-md-9 col-xs-8">
<input type="email" class="form-control" id="CustomerEmail" name="CustomerEmail" value="{{ old('CustomerEmail') }}">
</div>
</div>
<div class="form-group">
<label for="CustomerPhone" class="col-md-3 col-xs-4">手機號碼</label>
<div class="col-md-9 col-xs-8">
<input type="number" class="form-control" id="CustomerPhone" name="CustomerPhone" value="{{ old('CustomerPhone') }}">
</div>
</div>
<hr>
<div class="form-group">
<div class="col-md-offset-3 col-xs-offset-4 col-md-9 col-xs-8">
<select class="form-control" id="giveTongBian" name="giveTongBian">
<option value="no" #if(old('giveTongBian') === "no") selected #endif>不需統編</option>
<option value="yes" #if(old('giveTongBian') === "yes") selected #endif>輸入統編</option>
</select>
</div>
</div>
<div class="form-group" id="customerIdentGroup">
<label for="CustomerIdentifier" class="col-md-3 col-xs-4">統一編號</label>
<div class="col-md-9 col-xs-8">
<input type="text" class="form-control" id="CustomerIdentifier" name="CustomerIdentifier" value="{{ old('CustomerIdentifier') }}">
</div>
</div>
<div class="form-group" id="customerNameGroup">
<label for="CustomerName" class="col-md-3 col-xs-4">買受人</label>
<div class="col-md-9 col-xs-8">
<input type="text" class="form-control" id="CustomerName" name="CustomerName" value="{{ old('CustomerName') }}">
</div>
</div>
<div class="form-group" id="customerAddrGroup">
<label for="CustomerAddr" class="col-md-3 col-xs-4">地址</label>
<div class="col-md-9 col-xs-8">
<input type="text" class="form-control" id="CustomerAddr" name="CustomerAddr" value="{{ old('CustomerAddr') }}">
</div>
</div>
<div class="tappay-form col-xs-offset-1 col-xs-10">
<h4 style="color: darkkhaki;">信用卡</h4>
<div class="form-group card-number-group">
<label for="card-number" class="control-label"><span id="cardtype"></span>卡號</label>
<div class="form-control card-number"></div>
</div>
<div class="form-group expiration-date-group">
<label for="expiration-date" class="control-label">卡片到期日</label>
<div class="form-control expiration-date" id="tappay-expiration-date"></div>
</div>
<div class="form-group cvc-group">
<label for="cvc" class="control-label">卡片後三碼</label>
<div class="form-control cvc"></div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Pay</button>
</div>
</div>
</form>
I then have a on submit event which does a few things. At the bottom is me updating the hidden input with id = prime.
$('form').on('submit', function (event) {
//Code for first part of form begin
var boolFlag = true; //Default is submit
var errorMsg = ""; //Initial message
//Begin validation
var numOfNonEmptyFields = 0;
if(document.forms["paymentForm"]["CustomerEmail"].value != "") {
numOfNonEmptyFields++;
}
if(document.forms["paymentForm"]["CustomerPhone"].value != "") {
numOfNonEmptyFields++;
}
if(numOfNonEmptyFields == 0) {
errorMsg += "請輸入至少一個電子信箱或手機號碼.\n";
boolFlag = false;
}
//End validation
//Final steps: overall error message + success or fail case
if(boolFlag == false) {
alert("錯誤:\n" + errorMsg);
return false;
}
//Code for first part of form end
// fix keyboard issue in iOS device
forceBlurIos()
const tappayStatus = TPDirect.card.getTappayFieldsStatus()
console.log(tappayStatus)
// Check TPDirect.card.getTappayFieldsStatus().canGetPrime before TPDirect.card.getPrime
if (tappayStatus.canGetPrime === false) {
bootbox.alert({
title: "錯誤訊息",
message: "取得不了Prime.",
buttons: {
ok: {
label: "OK",
className: "btn btn-primary"
}
}
});
return false
}
// Get prime
TPDirect.card.getPrime(function (result) {
if (result.status !== 0) {
bootbox.alert({
title: "錯誤訊息",
message: result.msg,
buttons: {
ok: {
label: "OK",
className: "btn btn-primary"
}
}
});
return false
}
$("#prime").val(result.card.prime);
})
})
I've tested the hidden input with alert($("#prime").val()) directly after and it seems updated, however after submission, my Controller receives the value as null while other hidden input values are correct. So I suspect it's something got to do with the on submit event.
Added id attribute to the form element:
<form id="paymentForm" name="paymentForm" action="/parking_302/upload_payment" method="POST" role="form" class="form-horizontal">
Removed type from the button and added id:
<button id="submit-btn" class="btn btn-default">Pay</button>
Introduced a new click listener:
$(document).on("click","#submit-btn", function(event){
event.preventDefault();
validateAndSendForm();
});
Introduced a new function for the final form submit:
function submitForm(){
//do other stuff here with the finalized form and data
//.....
$( "#paymentForm" ).submit();
}
And put all of your old things into a new function as well:
function validateForm(){
//Code for first part of form begin
var boolFlag = true; //Default is submit
var errorMsg = ""; //Initial message
...
...
...
}
// Get prime
TPDirect.card.getPrime(function (result) {
if (result.status !== 0) {
bootbox.alert({
title: "錯誤訊息",
message: result.msg,
buttons: {
ok: {
label: "OK",
className: "btn btn-primary"
}
}
});
return false;
}
$("#prime").val(result.card.prime);
//use when you are ready to submit
submitForm();
})
}
So, basically you will have a "submitForm" function that you can use whenever you are ready to submit the form.
Seems like TPDirect.card.getPrime is something that gets data asynchronously so the $('form').on('submit' function won't wait for it to finish.

Show a preview/Edit option before submitting the form using AngularJS

I have my html form as shown below:
<div class="container">
<div class="form-group" ng-controller="studentController">
<form role="form" class="well form-horizontal" id="registerForm" name="forms.registerForm">
<div class="form-group">
<label class="col-md-4 control-label">First Name </label>
<input ng-model="formdata.firstname" required type="text" name="firstname">
</div>
<div class="form-group">
<label class="col-md-4 control-label">Middle Name </label>
<input ng-model="formdata.middlename" required type="text" name="middlename" maxlength="1">
</div>
<div class="form-group">
<label class="col-md-4 control-label">Last Name </label>
<input ng-model="formdata.lastname" required type="text" name="lastname">
</div>
<div class="form-group">
<label for="email" class="col-md-4 control-label">E-mail address</label>
<input ng-model="formdata.email" required type="email">
</div>
<div class="form-group">
<label class="col-md-4 control-label">Student ID</label>
<input ng-model="formdata.studentid" required type="number">
</div>
<div required class="form-group">
<label class="col-md-6 control-label">
level
</label> <br>
<div class="radio">
<label class="col-md-6 control-label">
<input type="radio" ng-model="formdata.type" value="300" checked>
300 </label>
</div>
<div class="radio">
<label class="col-md-6 control-label">
<input type="radio" ng-model="formdata.type" value="400">
400 </label>
</div>
<div class="radio">
<label class="col-md-6 control-label">
<input type="radio" ng-model="formdata.type" value="500">
500 </label>
</div>
</div>
<div class="form-group" align="center">
<input type="file" ngf-select ng-model="formdataa.file" name="file" ngf-pattern="'application/pdf'" accept="'.pdf'" ngf-max-size="5MB" required ngf-model-invalid="errorFile">
</div>
<div class="container" align="center">
<button class="btn btn-register" ng-click="tempData()" ng-disabled="forms.registerForm.$invalid" >Submit</button>
</div>
Below is the angular javascript code to store the details of the form and the file in the server.
$scope.tempData = function(ev){
console.log($scope.formdata);
var confirm = $mdDialog.confirm()
.title('Are you sure you want to delete this user?')
.ok('YES')
.cancel('CANCEL');
$mdDialog.show({
locals:{formdata: $scope.formdata, dataToPassFile: $scope.formdataa}, //here where we pass our data
controller: _DialogController,
controllerAs: 'vd',
templateUrl: 'scripts/app/studentdialog/studentdialog.html',
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose: true
})
.then(
function(answer) {},
function() {
}
);
};
function _DialogController($scope, $mdDialog, formdata,dataToPassFile) {
$scope.closeDialog = function() {
$mdDialog.hide();
};
$scope.firstname = formdata.firstname;
$scope.lastname = formdata.lastname;
$scope.middlename = formdata.middlename;
$scope.studentid = formdata.studentid;
$scope.email = formdata.email;
$scope.type = formdata.type;
$scope.file = dataToPassFile.file;
console.log('FIle Passed' +dataToPassFile.file);
$scope.tfile = function () {
console.log("TFIle Called");
if ($scope.forms.registerForm.file.$valid && $scope.formdataa.file) {
$scope.upload($scope.formdataa.file);
}
};
$scope.upload = function (file) {
file.upload = Upload.upload({
url: $rootScope.baseURL + 'php/uploadT.php',
method: 'POST',
data: {
'file': file,
'userId': $scope.formdata.firstname,
'type': $scope.formdata.type
},
});
$scope.register = function () {
console.log("clicked");
$scope.loading = true;
AppServices.register($scope.formdata)
.then(function (result) {
if (Object.keys(result).length > 0) {
// update current users list
if (result.type == '300' || result.type == '400') {
$scope.users.300.push(result);
} else {
console.log(result);
$scope.users[result.type] = result;
}
$scope.forms.registerForm.$setPristine();
$scope.forms.registerForm.$setUntouched();
$scope.msg = {};
$scope.msg.successRegister = 'Registered Successfully';
} else {
$scope.msg = {};
$scope.msg.errorRegister = 'Email already exists!';
}
})
.finally(function (data) {
$scope.loading = false;
});
};
When the user clicks on Submit button, I want to create a confirmation page where it will give the user all the details again so the user can confirm and then actually submit the form. Kindly let me know how can I use localStorage for storing and retrieving the data at the same time for confirm page.
Thank you in advance!
UPDATE: I created a MDDialog and calling it when the button is clicked,I can see all the data as well in MDDialog now. When user clicks on OK, I want the data on the page(not the data on the MDDialog) to be submited in the backend(php), how can I do that?
Why not show this info on a modal, and call the confirmation function in the same controller where you are, after the modal is closed. This way you won't need any caching policy.

How to enable disable a select drop down list using radio buttons with angularjs?

I have been searching all over for the internet looking on how to enable or disable this drop down list using radio buttons specifically when the radio button value is equal to prof the drop down list should be disabled, but with no help. I did come up with an example but didn't work. Any help would be appreciated.
registration.html
<div class="form-group">
<label class="col-lg-2 col-md-3 control-label">Qualification</label>
<div class="col-lg-10 col-md-9">
<div class="radio-custom radio-inline">
<input type="radio" ng-model="QualificationDetails.qualification_type" value="edu" name="radio1" id="radio4">
<label for="radio4">Educational</label>
</div>
<div class="radio-custom radio-inline">
<input type="radio" ng-model="QualificationDetails.qualification_type" value="prof" name="radio1" id="radio5">
<label for="radio5">professional</label>
</div>
</div>
</div>
//This is the drop down that I need to diable
<div class="form-group">
<label class="col-sm-2 control-label" for="Qulitype">Qualification type</label>
<div class="col-sm-10">
<select name="repeatSelect" id="repeatSelect" ng-disabled="QualificationDetails.qualification_type == 'prof'" ng-model="QualificationDetails.qualification" class="form-control">
<option ng-repeat="quali in qualiLevel" value="{{quali.qualification_id}}">{{quali.quali_level}}</option>
</select>
</div>
</div>
This is the code I implemented to work above scenario. But didn't work :(
regController.js
$scope.$watch('QualificationDetails.qualicication_type', function (QualiType) {
if (angular.isUndefined($scope.QualificationDetails)) {
return;
}
if (QualiType === 'prof') {
$scope.QualificationDetails.qualification_type = $scope.QualiType;
}
else {
if ($scope.QualificationDetails.qualification_type !== null) {
$scope.QualiType = $scope.QualificationDetails.qualification_type;
$scope.QualificationDetails.qualification_type = null;
}
}
});
the above scenario is that when it comes to qualifications if qualification type is equal to professional (prof) drop down list is disabled and when it is educational the drop down list should be enabled. Any idea on how to achieve this.
This is the Quality level json. I get it through the qualitylevel.service.
(function initController() {
deptService.getdepts(function (res) {
$scope.depts = JSON.parse(res.data);
});
qualiService.getquali(function (res) {
console.log("inside ");
$scope.qualiLevel = JSON.parse(res.data);
});
console.log("inside service");
})();
It seems to me, that your code works fine without watcher you have added. I hope I understood what you want correctly. Try this snippet:
angular
.module('app', [])
.controller('Ctrl', function($scope) {
$scope.qualiLevel = [
{quali_level: 'A', qualification_id: 1},
{quali_level: 'B', qualification_id: 2}
];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="Ctrl">
<div class="form-group">
<label class="col-lg-2 col-md-3 control-label">Qualification</label>
<div class="col-lg-10 col-md-9">
<div class="radio-custom radio-inline">
<input type="radio" ng-model="QualificationDetails.qualification_type" value="edu" name="radio1" id="radio4">
<label for="radio4">Educational</label>
</div>
<div class="radio-custom radio-inline">
<input type="radio" ng-model="QualificationDetails.qualification_type" value="prof" name="radio1" id="radio5">
<label for="radio5">professional</label>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label" for="Qulitype">Qualification type</label>
<div class="col-sm-10">
<select name="repeatSelect" id="repeatSelect" ng-disabled="QualificationDetails.qualification_type == 'prof'" ng-model="QualificationDetails.qualification" class="form-control">
<option ng-repeat="quali in qualiLevel" value="{{quali.qualification_id}}">{{quali.quali_level}}</option>
</select>
</div>
</div>
</div>
</div>
As the control is radiobutton, your QualificationDetails.qualification_type value will be set to 1 or 0 and not to the label value. You have to have different variables for two radio buttons. Based on their value you have to set QualificationDetails.qualification_type = 'prof' or something
You can also try $parent.QualificationDetails.qualification_type instead as answered in How can I get the value of the checked radio button when submitting a form using angularjs?
Thanks everyone for helping me out. Just felt wanted to show I implemented it correctly and other programmers to increase their knowledge. Using $watch to temporaly hide the drop down list details).
the registrationController.js
$scope.$watch('QualificationDetails.qualification_type', function (Val) {
if (angular.isUndefined($scope.QualificationDetails))
return;
if (Val !== 'prof') {
$scope.QualificationDetails.qualification = $scope.tempValue;
}
else {
if ($scope.QualificationDetails.qualification !== null) {
$scope.tempValue = $scope.QualificationDetails.qualification;
$scope.QualificationDetails.qualification = null;
}
}
});
Implemented through this example.

Categories