I want to know if my radio button and checkbox are checked. If so I will save the change in the database.
Here is my form code :
<SCRIPT>
function set(target) {
var val1;
if (target == 'save') {
val1 = getradiovalue('officialForCalculation');
document.forms[1].selectedOfficialCalc.value = val1;
}
document.forms[1].button.value= target;
document.forms[1].submit();
}
function getradiovalue(rad) {
var rad_val;
if (rad == 'officialForCalculation')
if (document.forms[1].officialCalculation) {
if (!document.forms[1].officialCalculation[1]) {
if (document.forms[1].officialCalculation.checked) {
rad_val = document.forms[1].officialCalculation.value;
}
} else {
for (var i = 1; i < document.forms[1].officialCalculation.length; i++) {
if (document.forms[1].officialCalculation[i].checked) {
rad_val = document.forms[1].officialCalculation[i].value;
}
}
}
}
return rad_val;
}
</SCRIPT>
<form action="/getAll.do" name="table">
<logic:present name="frmTransitionMatrix" property="matrixes">
<logic:iterate name="frmTransitionMatrix" property="matrixes" id="matrixid">
<c:if test="${matrixid.officialForCalculation=='1'}">
<td align="center" width="25%"><input type="radio"
name="officialForCalculation"
value="<bean:write
name="matrixid" property="idTransitionMatrix"/>" checked='checked'/>
</td>
</c:if>
<c:if test="${matrixid.officialForCalculation=='0'}">
<td align="center" width="25%"><input type="radio"
name="officialForCalculation"
value="<bean:write name="matrixid" property="idTransitionMatrix"/>"/>
</td>
</c:if>
<logic:equal value="1" name="matrixid" property="active">
<td align="center" width="25%"><input type="checkbox"
name="activeMatrix"
value="<bean:write name="matrixid" property="idTransitionMatrix"/>"
checked /></td>
</logic:equal>
<logic:equal value="0" name="matrixid" property="active">
<td align="center" width="25%"><input type="checkbox"
name="activeMatrix"
value="<bean:write name="matrixid" property="idTransitionMatrix"/>"/>
</td>
</logic:equal>
</tr>
</logic:iterate>
</logic:present>
<input type="button" name="button" value="Save" class="button" onClick="set('save');"/>
</form>
Here is my MatrixForm
#Data
public class MatrixForm extends ActionForm {
private List<MatrixEntity> matrixes = new ArrayList<MatrixEntity>();
private String allMatrixes;
private String selectedOfficialCalc;
private String[] activeMatrix;
}
My Action class
public ActionForward updateAll(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws DBAccessException, TimeOutException {
MatrixForm faForm = (MatrixForm) form;
MatrixDaoImpl matrixDao = new MatrixDaoImpl();
String MatrixForCalc = faForm.getSelectedOfficialCalc();
List<String> validForCalcList = new ArrayList<String>();
validForCalcList.add(MatrixForCalc);
String[] activeMatrix = faForm.getActiveMatrix();
List<String> actMatrixsList = new ArrayList<String>();
if (activeMatrix != null) {
for (int i = 0; i < activeMatrix.length; i++) {
actMatrixsList.add(activeMatrix[i]);
}
}
List<MatrixEntity> matrixes = faForm.getMatrixes();
MatrixEntity Entity;
if (matrixes != null && !matrixes.isEmpty()) {
for (MatrixEntity matrix : matrixes) {
if (validForCalcList != null && !validForCalcList.isEmpty()
&& validForCalcList.contains(matrix.getIdTransitionMatrix())) {
if (!actMatrixsList.contains(matrix.getIdTransitionMatrix())) {
//getB2SContext(request).setErrorInfo("The Official Portfolio for Calculation cannot be inactive");
return mapping.findForward("active");
}
}
}
for (int count = 0; count < matrixes.size(); count++) {
Entity = matrixes.get(count);
if (validForCalcList != null && !validForCalcList.isEmpty()
&& validForCalcList.contains(Entity.getIdTransitionMatrix())) {
if (!actMatrixsList.contains(Entity.getIdTransitionMatrix())) {
//getB2SContext(request).setErrorInfo("The Official Portfolio for Calculation cannot be inactive");
return mapping.findForward("active");
} else {
Entity.setActive(BigInteger.ONE);
Entity.setOfficialForCalculation(BigInteger.ONE);
}
} else {
if (actMatrixsList.contains(Entity.getIdTransitionMatrix())) {
Entity.setActive(BigInteger.ONE);
} else {
Entity.setActive(BigInteger.ZERO);
}
Entity.setOfficialForCalculation(BigInteger.ZERO);
}
}
matrixDao.updateAll(matrixes);
}
I have debugged my code and I've found that activeMatrix is null even if it's checked and the same thing occurs for selectedOfficialCalc. I want to know how I can set the properties of my MatrixForm if they are checked.
Related
I've got a text field which allows users to enter their location which returns results (cities) from the Google Places API. Here's the code I'm using to fill in my form fields once a user has selected a location:
function fillInAddress() {
// Get the place details from the autocomplete object.
var place = autocomplete.getPlace();
var lat = place.geometry.location.lat().toFixed(6);
var lng = place.geometry.location.lng().toFixed(6);
var components = place.address_components;
for (var i = 0, component; component = components[i]; i++) {
if (component.types[0] == 'locality') {
$('#id_city').val(component['long_name'])
}
if (component.types[0] == 'administrative_area_level_1') {
$('#id_state').val(component['short_name'])
}
if (component.types[0] == 'country') {
$('#id_country_short').val(component['short_name'])
}
if (component.types[0] == 'country') {
$('#id_country_long').val(component['long_name'])
}
if (component.types[0] == 'sublocality_level_1') {
$('#id_region').val(component['long_name'])
}else{
$('#id_region').val('')
}
}
$('#lat').val(lat)
$('#lng').val(lng)
}
Pretty straight forward, but there's not always a "region" (or sublocality_level_1) selected with their location. What I'm attempting to do is clear the #id_region field of any old regions if the new location they've selected does not have a region/sublocality_level_1. The problem is that even if a sublocality_level_1 is present, the code still seems to hit the "else" statement which clears the #id_region text field.
Any idea what I'm doing wrong here?
The problem exists because of the structure of your if...else for a region. Because you are in a loop if there is any component in the components array after the one that is a region it will ... clear the region.
Remove the else from the loop. Clear the region before you start looping. That way if there is a region in the set, you'll fill it in and if there isn't it will stay empty.
function fillInAddress() {
// Get the place details from the autocomplete object.
var place = autocomplete.getPlace();
var lat = place.geometry.location.lat().toFixed(6);
var lng = place.geometry.location.lng().toFixed(6);
var components = place.address_components;
$('#id_region').val('');
for (var i = 0, component; component = components[i]; i++) {
if (component.types[0] == 'locality') {
$('#id_city').val(component['long_name'])
}
if (component.types[0] == 'administrative_area_level_1') {
$('#id_state').val(component['short_name'])
}
if (component.types[0] == 'country') {
$('#id_country_short').val(component['short_name'])
}
if (component.types[0] == 'country') {
$('#id_country_long').val(component['long_name'])
}
if (component.types[0] == 'sublocality_level_1') {
$('#id_region').val(component['long_name'])
}
}
$('#lat').val(lat)
$('#lng').val(lng)
}
In addition to what #gforce301 said, you also need to process through all the types in the component:
var components = place.address_components;
$('#id_region').val('')
for (var i = 0, component; component = components[i]; i++) {
for (var j = 0; j < component.types.length; j++) {
if (component.types[j] == 'locality') {
$('#id_city').val(component['long_name'])
}
if (component.types[j] == 'administrative_area_level_1') {
$('#id_state').val(component['short_name'])
}
if (component.types[j] == 'country') {
$('#id_country_short').val(component['short_name'])
}
if (component.types[j] == 'country') {
$('#id_country_long').val(component['long_name'])
}
if (component.types[j] == 'sublocality_level_1') {
$('#id_region').val(component['long_name'])
}
}
proof of concept fiddle
(places with sublocality_level_1: Brooklyn, NY; Śródmieście, Warsaw, Poland)
code snippet:
function initAutocomplete() {
// Create the autocomplete object, restricting the search to geographical
// location types.
autocomplete = new google.maps.places.Autocomplete(
/** #type {!HTMLInputElement} */
(document.getElementById('autocomplete')), {
types: ['geocode']
});
// When the user selects an address from the dropdown, populate the address
// fields in the form.
autocomplete.addListener('place_changed', fillInAddress);
}
google.maps.event.addDomListener(window, "load", initAutocomplete);
function fillInAddress() {
// Get the place details from the autocomplete object.
var place = autocomplete.getPlace();
var lat = place.geometry.location.lat().toFixed(6);
var lng = place.geometry.location.lng().toFixed(6);
var components = place.address_components;
$('#id_region').val('')
for (var i = 0, component; component = components[i]; i++) {
for (var j = 0; j < component.types.length; j++) {
if (component.types[j] == 'locality') {
$('#id_city').val(component['long_name'])
}
if (component.types[j] == 'administrative_area_level_1') {
$('#id_state').val(component['short_name'])
}
if (component.types[j] == 'country') {
$('#id_country_short').val(component['short_name'])
}
if (component.types[j] == 'country') {
$('#id_country_long').val(component['long_name'])
}
if (component.types[j] == 'sublocality_level_1') {
$('#id_region').val(component['long_name'])
} else {
// $('#id_region').val('')
}
}
}
$('#lat').val(lat)
$('#lng').val(lng)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<div id="locationField">
<input id="autocomplete" placeholder="Enter your address" type="text" />
</div>
<table id="address">
<tr>
<td class="label">Street address</td>
<td class="slimField">
<input class="field" id="street_number" disabled="true" />
</td>
<td class="wideField" colspan="2">
<input class="field" id="route" disabled="true" />
</td>
</tr>
<tr>
<td class="label">City</td>
<!-- Note: Selection of address components in this example is typical.
You may need to adjust it for the locations relevant to your app. See
https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform
-->
<td class="wideField" colspan="3">
<input class="field" id="id_city" disabled="true" />
</td>
</tr>
<tr>
<td class="label">State</td>
<td class="slimField">
<input class="field" id="id_state" disabled="true" />
</td>
<td class="label">Region</td>
<td class="wideField">
<input class="field" id="id_region" disabled="true" />
</td>
</tr>
<tr>
<td class="label">Country</td>
<td class="wideField" colspan="3">
<input class="field" id="id_country_long" disabled="true" />
</td>
</tr>
<tr>
<td class="label">Country</td>
<td class="wideField" colspan="3">
<input class="field" id="id_country_short" disabled="true" />
</td>
</tr>
</table>
<input id="lat" />
<input id="lng" />
I want to do something like this within my view (razor)
if(index == #:{<script>{getPosition(#geResult.assessmentId);}</script>}){
geResult.ResultValue;
}
What will be the proper syntax?
Full HTML
<tr>
#{
var index = 4;
foreach(Assessment geAssessment in Model.assessments)
{
<td>
#foreach (ShortResult geResult in Model.results)
{
if(geResult.StudentID == geStudent.studentid)
{
if(index == #:{<script>{getPosition(#geResult.assessmentId);}</script>} ){
geResult.ResultValue;
}
}
}
</td>
index++;
}
}
</tr>
UPDATE
I am trying the other way round now can anyone guide me please
SCRIPT
function getPosition(id, colIndex) {
var element = '#' + id;
$(this).closest('tr').find('td').eq(colIndex).html("A");
alert($(this).closest('tr').find('td').eq(colIndex).html());
return $(element).index();
}
HTML
<td>
#foreach (ShortResult geResult in Model.results)
{
if(geResult.StudentID == geStudent.studentid)
{
<script>{ getPosition(#geResult.assessmentId, #index); }</script>
}
}
</td>
now the alert returns undefined although i am setting its value (text) just before!!
Finally, after wasting a whole 1.5 days i am able to solve this! hope it helps someone.
SCRIPT
function getPosition(id, colIndex, resultValue) {
var element = '#' + id;
var cell = $('.test').closest('tr').children('td').get(colIndex);
if($(element).index() == colIndex){
cell.innerHTML = resultValue;
}
}
HTML
<tr>
#{
var index = 4;
foreach(Assessment geAssessment in Model.assessments)
{
<td class="test">
#foreach (ShortResult geResult in Model.results)
{
if(geResult.StudentID == geStudent.studentid)
{
if (geResult.ResultValue != null) {
<script>{ getPosition(#geResult.assessmentId, #index, '#geResult.ResultValue'); }</script>
}
}
}
</td>
index++;
}
}
</tr>
The issue is that it appears that non of my JavaScript is working and I've spent hours trying to figure out why, I can't find any obvious errors and I'm fairly new to JavaScript in general, but i'm trying to get JavaScript to validate the code in my form together with regEx and as of right now its not doing anything.
Heres the code for my Form:
<form action="ValideringVM.php" method="post" name="Registrer" onsubmit="return valider_alle()">
<table>
<tr>
<td><h3> Personalia:</h3> </td>
</tr>
<tr>
<td> Fornavn: </td>
<td><input type="text" name="Fornavn" onChange="valider_fornavn()"/></td>
<td><div id="FeilFornavn">*</div></td>
</tr>
<tr>
<td> Etternavn: </td>
<td><input type="text" name="Etternavn" onChange="valider_etternavn()"/></td>
<td><div id="FeilEtternavn">*</div></td>
</tr>
<tr>
<td> Adresse: </td>
<td><input type="text" name="Adresse" onChange="valider_adresse()"/></td>
<td><div id="FeilAdresse">*</div></td>
</tr>
<tr>
<td> Postnr: </td>
<td><input type="text" name="Postnr" onChange="valider_postnr()"/></td>
<td><div id="FeilPostnr">*</div></td>
</tr>
<tr>
<td> Email: </td>
<td><input type="text" name="Email" onChange="valider_email()"/></td>
<td><div id="FeilEmail">*</div></td>
</tr>
<tr>
<td> Telefonnr: </td>
<td><input type="text" name="Telefonnr" onChange="valider_telefonnr()"/></td>
<td><div id="FeilTelefonnr">*</div></td>
</tr>
<tr>
<td> Lag Brukernavn: </td>
<td><input type="text" name="Brukernavn" onChange="valider_brukernavn()"/></td>
<td><div id="Feilbruker">*</div></td>
</tr>
<tr>
<td> Lag Passord: </td>
<td><input type="password" name="Passord" onChange="valider_passord()"/></td>
<td><div id="Feilpassord">*</div></td>
</tr>
<tr>
<td><input type="submit" name="Send" value="Send"/></td>
</tr>
</table>
</form>
and heres my Javascript code:
<script type="text/javascript">
function valider_fornavn()
{
regEx = /^[a-zA-ZæøåÆØÅ .\- ](2,20)$/;
OK = regEx.test(document.Registrer.Fornavn.value);
if(!OK)
{
document.getElementById("FeilFornavn").innerHTML="Feil i Fornavn";
return false;
}
document.getElementById("FeilFornavn").innerHTML="";
return true;
}
function valider_etternavn()
{
regEx = /^[a-zA-ZæøåÆØÅ .\- ](2,20)$/;
OK = regEx.test(document.Registrer.Etternavn.value);
if(!OK)
{
document.getElementById("FeilEtternavn").innerHTML="Feil i Etternavn";
return false;
}
document.getElementById("FeilEtternavn").innerHTML="";
return true;
}
function valider_adresse()
{
regEx = /^[a-zA-ZæøåÆØÅ 0-9.\- ](2,30)$/;
OK = regEx.test(document.Registrer.Adresse.value);
if(!OK)
{
document.getElementById("FeilAdresse").innerHTML="Feil i Adresse";
return false;
}
document.getElementById("FeilAdresse").innerHTML="";
return true;
}
function valider_postnr()
{
regEx = /^[0-9](4)$/;
OK = regEx.test(document.Registrer.Postnr.value);
if(!OK)
{
document.getElementById("FeilPostnr").innerHTML="Feil i Postnr";
return false;
}
document.getElementById("FeilPostnr").innerHTML="";
return true;
}
function valider_email()
{
regEx = /^[a-zA-ZæøåÆØÅ 0-9._%+-]+#[a-zA-ZæøåÆØÅ 0-9.-]+\.[a-z]{2,4}$/;
OK = regEx.test(document.Registrer.Email.value);
if(!OK)
{
document.getElementById("FeilEmail").innerHTML="Feil i Email";
return false;
}
document.getElementById("FeilEmail").innerHTML="";
return true;
}
function valider_telefonnr()
{
regEx = /^[0-9]{8}$/;
OK = regEx.test(document.Registrer.Telefonnr.value);
if(!OK)
{
document.getElementById("FeilTelefonnr").innerHTML="Feil i Telefonnummer";
return false;
}
document.getElementById("FeilTelefonnr").innerHTML="";
return true;
}
function valider_brukernavn()
{
regEx = /^[a-zA-ZæøåÆØÅ 0-9](4,20)$/;
OK = regEx.test(document.Registrer.Brukernavn.value);
if(!OK)
{
document.getElementById("Feilbruker").innerHTML="Feil i brukernavnet";
return false;
}
document.getElementById("FeilBruker").innerHTML="";
return true;
}
function valider_passord()
{
regEx = /^[a-zA-ZæøåÆØÅ 0-9](4,20)$/;
OK = regEx.test(document.Registrer.Passord.value);
if(!OK)
{
document.getElementById("FeilPassord").innerHTML="Feil i passordet";
return false;
}
document.getElementById("FeilPassord").innerHTML="";
return true;
}
function valider_alle()
{
(e || window.event).preventDefault();
FornavnOK = valider_fornavn();
EtternavnOK = valider_etternavn();
AdresseOK = valider_adresse();
PostnrOK = valider_postnr();
TelefonnrOK = valider_telefonnr();
EmailOK = valider_email();
BrukernavnOK = valider_brukernavn();
PassordOK = valider_passord();
}
if(FornavnOK && EtternavnOK && AdresseOK && PostnrOK && TelefonnrOK && EmailOK && BrukernavnOK && PassordOK)
{
return true;
}
else
{
return false;
}
</script>
last function valider_alle end brace is not set to its right place
function valider_alle()
{
(e || window.event).preventDefault();
FornavnOK = valider_fornavn();
EtternavnOK = valider_etternavn();
AdresseOK = valider_adresse();
PostnrOK = valider_postnr();
TelefonnrOK = valider_telefonnr();
EmailOK = valider_email();
BrukernavnOK = valider_brukernavn();
PassordOK = valider_passord();
//} this one must be at the end
if(FornavnOK && EtternavnOK && AdresseOK && PostnrOK && TelefonnrOK && EmailOK && BrukernavnOK && PassordOK)
{
return true;
}
else
{
return false;
}
}
and if you are ensuring that the length is between 2 and 20 like that:
regEx = /^[a-zA-ZæøåÆØÅ .\- ](2,20)$/;// ( and ) is not for length
it must be written:
regEx = /^[a-zA-ZæøåÆØÅ .\- ]{2,20}$/;
I've this HTML code:
<fieldset class="rpni-border">
<legend class="rpni-border">Model</legend>
<table id="contenedorModelos" style="" class="table table-condensed">
<tbody id="modeloBody">
<tr>
<td>
<input type="radio" value="1" id="selModelo1" name="selModelos">
</td>
<td>Harum.</td>
</tr>
<tr>
<td>
<input type="radio" value="4" id="selModelo4" name="selModelos">
</td>
<td>Pariatur ut.</td>
</tr>
<tr>
<td>
<input type="radio" value="6" id="selModelo6" name="selModelos">
</td>
<td>Tempore animi.</td>
</tr>
<tr>
<td>
<input type="radio" value="8" id="selModelo8" name="selModelos">
</td>
<td>Voluptatem.</td>
</tr>
</tbody>
</table>
</fieldset>
<fieldset class="rpni-border">
<legend class="rpni-border">Branch</legend>
<table id="contenedorMarcas" style="" class="table table-condensed">
<tbody id="marcaBody">
<tr>
<td>
<input type="radio" value="3" id="selMarca3" name="selMarcas">
</td>
<td>Ea in sequi.</td>
</tr>
<tr>
<td>
<input type="radio" value="7" id="selMarca7" name="selMarcas">
</td>
<td>Exercitationem.</td>
</tr>
<tr>
<td>
<input type="radio" value="11" id="selMarca11" name="selMarcas">
</td>
<td>Sit alias sit.</td>
</tr>
</tbody>
</table>
</fieldset>
<fieldset class="rpni-border">
<legend class="rpni-border">Manufacturer</legend>
<table id="contenedorFabricante" style="" class="table table-condensed">
<tbody id="fabricanteBody">
<tr>
<td>
<input type="checkbox" value="3">
</td>
<td>Ea in sequi.</td>
</tr>
<tr>
<td>
<input type="checkbox" value="7">
</td>
<td>Exercitationem.</td>
</tr>
<tr>
<td>
<input type="checkbox" value="11">
</td>
<td>Sit alias sit.</td>
</tr>
</tbody>
</table>
</fieldset>
<button id="create" type="button">Create</button>
<div id="ModelBranch"></div>
<button id="createM" type="button">Join Model-Branch with Manufacturer</button>
<div id="ModelBranchManufacturer"></div>
And then there is this jQuery:
$(document).ready(function () {
function modelBranchManufacturerObject(config) {
var instance = this;
// initialize class vars
instance.modelKey = config.modelKey;
instance.branchKey = config.branchKey;
instance.manufacturerKeyCollection = [];
instance.globalKey;
// globalKey = modelKey + branchKey
instance.getGlobalKey = function () {
if (!instance.globalKey) {
instance.globalKey = instance.modelKey + '-' + instance.branchKey;
}
return instance.globalKey;
}
instance.addManufacturerKeyCollection = function (manufacturerArray) {
instance.manufacturerKeyCollection = manufacturerArray;
}
}
var modelBranchManufacturerCollection = {};
function addNewRelationModelBranch(modelKey, branchKey) {
var tempModelBranchManufacturerObjectInstance = new modelBranchManufacturerObject({
modelKey: modelKey,
branchKey: branchKey
});
var globalKey = tempModelBranchManufacturerObjectInstance.getGlobalKey();
if (!modelBranchManufacturerCollection[globalKey]) {
modelBranchManufacturerCollection[globalKey] = tempModelBranchManufacturerObjectInstance;
} else {
return false;
}
return tempModelBranchManufacturerObjectInstance;
}
function addNewRelationModelBranchManufacturer(globalKey, manufacturerArray) {
if (modelBranchManufacturerCollection[globalKey]) {
modelBranchManufacturerCollection[globalKey].manufacturerKeyCollection = manufacturerArray;
} else {
return false;
}
return modelBranchManufacturerCollection;
}
var html = '<table><tbody id="branchModel"></tbody></table>';
$("#ModelBranch").html(html);
$("#create").on("click", function () {
var currModel = $("#modeloBody").find("input[type='radio']:checked").val(),
currBranch = $("#marcaBody").find("input[type='radio']:checked").val(),
ModelBranchObject, tr;
if (currModel && currBranch) {
ModelBranchObject = addNewRelationModelBranch(currModel, currBranch);
if (ModelBranchObject) {
tr = '<tr><td><input type="checkbox" value="' + ModelBranchObject.globalKey + '" /></td>';
tr += '<td>' + ModelBranchObject.modelKey + '-' + ModelBranchObject.branchKey + '</td></tr>';
$("#branchModel").append(tr);
}
}
});
var htmlManufacturer = '<table><tbody id="branchModelManufacturer"></tbody></table>';
$("#ModelBranchManufacturer").html(htmlManufacturer);
$("#createM").on("click", function () {
var checkedModelBranch = $("#branchModelManufacturer").find("input[type='checkbox']:checked"),
checkedManufacturers = $("#fabricanteBody").find("input[type='checkbox']:checked"),
manufacturerColl = [],
trManufacturer,
ModelBranchManufacturerObject;
for (var j = 0; j < checkedManufacturers.length; j++) {
manufacturerColl.push(checkedManufacturers[j].value);
}
console.log(manufacturerColl);
for (var i = 0; i < checkedModelBranch.length; i++) {
ModelBranchManufacturerObject = addNewRelationModelBranchManufacturer(checkedModelBranch[i].value, manufacturerColl);
console.log(ModelBranchManufacturerObject);
if (ModelBranchManufacturerObject) {
trManufacturer = '<tr><td><input type="checkbox" value="' + ModelBranchManufacturerObject.globalKey + '" /></td>';
trManufacturer += '<td>' + ModelBranchObject.modelKey + '-' + ModelBranchObject.branchKey;
for (var k = 0; k < ModelBranchObject.manufacturerKeyCollection.length; k++) {
trManufacturer += ModelBranchObject.manufacturerKeyCollection[k] + '<br/>';
}
trManufacturer += '</td></tr>';
$("#branchModelManufacturer").append(trManufacturer);
}
console.log(trManufacturer);
}
});
});
What this code does is allow to pick a model and a branch and create a non repeated pairs between them and also show the results on #modelBranch div. Also allow, I think if I'm not doing something wrong, to pick one|many choices from the results in the previous step (those on #modelBranch) and one|many Manufacturers and again create a non repeated pairs between them but in this case I can not show the results on #ModelBranchManufacturer as I should do so something is not working on my code and I was not able to find where I'm failing so certainly I need some help or advice from you. For clear a bit how the process is take a look at the following example:
Pick Model1/Branch1 and click on "Create Model/Branck Pair", this will generate a pair Model1-Branch1 as image below shows.
Pick Model1/Branch2 and click on "Create Model/Branck Pair", this will generate a pair Model1-Branch2 as image below shows.
Pick Model1/Branch1 and click on "Create Model/Branck Pair", nothing will happen since this pair was added on the (1) step and this is the right behavior to follow meaning do not allow repeated pairs
Now taking the example above you should have a table like this:
checkbox Model1-Branch1
checkbox Model1-Branch2
Following with the logic now:
Pick Model1/Branch1 and Model1/Branch2 pairs and from the Manufacturers table pick Manufacturer1 and click on "Create Model/Branck-Manufacturer Pair", this should generate something like this below:
Mark to Delete | Model/Branch | Manufacturer
----------------------------------------------------
checkbox | Model1-Branch1 | Manufacturer1
checkbox | Model1-Branch2 | Manufacturer1
Pick Model1/Branch1 and Model1/Branch2 pairs and from the Manufacturers table pick Manufacturer1 and Manufacturer2 and Manufacturer3 and click on "Create Model/Branck-Manufacturer Pair", this should generate something like this below:
Mark to Delete | Model/Branch | Manufacturer
----------------------------------------------------
checkbox | Model1-Branch1 | Manufacturer1
| | Manufacturer2
| | Manufacturer3
----------------------------------------------------
checkbox | Model1-Branch2 | Manufacturer1
| | Manufacturer2
| | Manufacturer3
Pick Model1/Branch1 and Model1/Branch2 pairs and from the Manufacturers table pick Manufacturer1 and click on "Create Model/Branck-Manufacturer Pair", nothing should happen since this pair was added on the (1) step and this is the right behavior to follow meaning do not allow repeated pairs
So, why the results from #createM on click event are not show in #ModelBranchManufacturer? Where I'm making something wrong in my code? I made this Fiddle for testing purpose
Ok, after some hours of coffee and a lot of headaches I got the solution and it's working. Maybe this code is a bit different from the main on the post since I made some changes but the idea still:
function modelBranchManufacturerObject(config) {
var instance = this;
// initialize class vars
instance.modelKey = config.modelKey;
instance.branchKey = config.branchKey;
instance.manufacturerCollection = [];
instance.modelName = config.modelName || 'Sin nombre asignado';
instance.branchName = config.branchName || 'Sin nombre asignado';
instance.globalKey;
// globalKey = modelKey + branchKey
instance.getGlobalKey = function () {
if (!instance.globalKey) {
instance.globalKey = instance.modelKey + '-' + instance.branchKey;
}
return instance.globalKey;
}
}
var modelBranchManufacturerCollection = {};
function addNewRelationModelBranch(modelKey, branchKey, modelName, branchName) {
var tempModelBranchManufacturerObjectInstance = new modelBranchManufacturerObject({
modelKey: modelKey,
branchKey: branchKey,
modelName: modelName,
branchName: branchName
});
var globalKey = tempModelBranchManufacturerObjectInstance.getGlobalKey();
if (!modelBranchManufacturerCollection[globalKey]) {
modelBranchManufacturerCollection[globalKey] = tempModelBranchManufacturerObjectInstance;
} else {
return false;
}
return tempModelBranchManufacturerObjectInstance;
}
function addNewRelationModelBranchManufacturer(globalKey, manufacturerArray) {
var manufacturerCollection = modelBranchManufacturerObject.manufacturerCollection;
if (modelBranchManufacturerCollection[globalKey]) {
if (manufacturerCollection !== manufacturerArray) {
modelBranchManufacturerCollection[globalKey].manufacturerKeyCollection = manufacturerArray;
return modelBranchManufacturerCollection[globalKey];
}
} else {
return false;
}
}
$("#btnCrearParMarcaModelo").on("click", function () {
var currModel = $("#modeloBody").find("input[type='radio']:checked").val(),
currBranch = $("#marcaBody").find("input[type='radio']:checked").val(),
currModelName = $("#modeloBody").find("input[type='radio']:checked").parent().next('td').text(),
currBranchName = $("#marcaBody").find("input[type='radio']:checked").parent().next('td').text(),
ModelBranchObject, tr;
if (currModel && currBranch) {
ModelBranchObject = addNewRelationModelBranch(currModel, currBranch, currModelName, currBranchName);
if (ModelBranchObject) {
tr = '<tr><td><input type="checkbox" value="' + ModelBranchObject.globalKey + '" /></td>';
tr += '<td>' + ModelBranchObject.modelName + '-' + ModelBranchObject.branchName + '</td><td id="' + ModelBranchObject.globalKey + '"></td></tr>';
$("#parMarcaModeloFabricanteBody").append(tr);
}
}
$("#parMarcaModeloFabricante").show();
});
$("#btnAgregarSelFabricante").on("click", function () {
console.log("d");
var checkedModelBranch = $("#parMarcaModeloFabricanteBody").find("input[type='checkbox']:checked"),
checkedManufacturers = $("#selFabricanteBody").find("input[type='checkbox']:checked"),
manufacturerColl = [],
modelBranchManufacturerCollection;
var j = checkedManufacturers.length, item;
while (j--) {
item = checkedManufacturers[j];
if (item.type && item.type == 'checkbox' && item.checked) {
manufacturerColl.push({
id: item.value,
name: item.parentNode.nextSibling.innerHTML
});
}
}
for (var i = 0; i < checkedModelBranch.length; i++) {
modelBranchManufacturerCollection = addNewRelationModelBranchManufacturer(checkedModelBranch[i].value, manufacturerColl);
if (modelBranchManufacturerCollection) {
//$("#parMarcaModeloFabricanteBody td#" + checkedModelBranch[i].value).siblings().attr("rowspan", modelBranchManufacturerCollection.manufacturerKeyCollection.length);
for (var k = 0; k < modelBranchManufacturerCollection.manufacturerKeyCollection.length; k++) {
$("#parMarcaModeloFabricanteBody td#" + checkedModelBranch[i].value).append((modelBranchManufacturerCollection.manufacturerKeyCollection)[k].name + '<br/>');
}
}
}
});
i made my form in table mode
like this:
<form name="register" method="post" action="#" onSubmit="return validasi()">
<table width="507" border="0">
<h1 class="title">Form Perubahan Password</h1>
<tr>
<td width="190" ><span id="usernameerror" class="style20">Masukkan Username </span></td>
<td width="319"><input name="username" type="text"></td>
</tr>
<tr>
<td><span id="passworderror" class="style20">Masukkan Password Lama</span></td>
<td><input name="pass" type="password"></td>
</tr>
<tr>
<td><span id="password1error" class="style20">Masukkan Password Baru</span></td>
<td><input name="pass1" type="password"></td>
</tr>
<tr>
<td><span id="password2error" class="style20">Ulangi Masukkan Password Baru</span></td>
<td><input name="pass2" type="password"></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="Submit" value="Submit">
<input type="reset" name="reset" value="Reset"></td>
</tr>
</table>
</form>
and this my validation code with javascript. check it out..
<script language="javascript">
function checkName(register)
{
var eobj = document.getElementById('usernameerror');
var susername = register.username.value;
var oRE = /^[a-z0-9]+[_.-]?[a-z0-9]+$/i;
var error = false;
eobj.innerHTML = '';
if (susername == '') {
error = 'Error: Username tidak boleh kosong';
register.username.focus();
}
else if (!oRE.test(susername))
{
error="Salah format";
}
if (error)
{
register.username.focus();
eobj.innerHTML = error;
return false;
}
return true;
}
function validatePwd(register) /* old password verification */
{
var eobj = document.getElementById('passworderror');
var invalid = ' ';
var pw = register.pass.value;
var error = false;
eobj.innerHTML = '';
if (pw.length < 1)
{
error = 'Masukkan password anda';
}
else if (pw.indexOf(invalid) > -1)
{
error = 'Anda harus mengisi password';
}
if (error)
{
register.pass.focus();
eobj.innerHTML = error;
return false
}
return true;
}
function validatePwd1(register) /* password & retype-password verification */
{
var eobj1 = document.getElementById('password1error');
var eobj2 = document.getElementById('password2error');
var invalid = ' ';
var pw1 = register.pass1.value;
var pw2 = register.pass2.value;
var error = false;
eobj1.innerHTML = '';
eobj2.innerHTML = '';
if (pw1.length < 1)
{
error = 'Masukkan password anda';
}
else if (pw1.indexOf(invalid) > -1)
{
error = 'Anda harus mengisi password';
}
if (error)
{
register.pass1.focus();
eobj1.innerHTML = error;
return false
}
if (pw1 != pw2)
{
eobj2.innerHTML = ' password tidak sama, coba masukkan kembali password anda';
return false;
}
return true;
}
function validasi()
{
var form = document.forms['register'];
var ary = [checkName, validatePwd, validatePwd1];
var rtn = true;
var z0 = 0;
for (var z0 = 0; z0 < ary.length; z0++)
{
if (!ary[z0](form))
{
rtn = false;
}
}
return rtn;
}
</script>
When i use this validation in usually form its work But in table mode that's validation code doesn't work..help me to solve this problem...tq
view demo
http://jsfiddle.net/andricoga/u9eZz/
You have declared onSubmit="return validasi()" in form , but where you defined function for that. for validation working you need to define function for that.
function validasi(){
// validation code goes here
}
In your validatePwd() function replace
eobj1.innerHTML = error;
with
eobj.innerHTML = error;
you have not defined this eobj1 object and hence it is causing a run time javascript error.
I changed the code to display the error beside the field, try this out
Javascript
<script language="javascript">
function checkName()
{
var obj = document.getElementById('usernameerror');
var susername = document.getElementById('username').value;
var oRE = /^[a-z0-9]+[_.-]?[a-z0-9]+$/i;
var error = false;
obj.innerHTML = '';
if (susername == '') {
error = 'Username can not be empty';
}
else if (!oRE.test(susername))
{
error = 'One format';
}
if (error)
{
document.getElementById('username').focus();
obj.innerHTML = error;
return false;
}
return true;
}
function validatePwd() /* password & retype-password verification */
{
var obj = document.getElementById('pwderror');
var invalid = ' ';
var pw = document.getElementById('pass').value;
var error = false;
obj.innerHTML = '';
if (pw.length < 1)
{
error = 'Enter your old password';
}
else if (pw.indexOf(invalid) > -1)
{
error = 'You need a password';
}
if (error)
{
document.getElementById('pass').focus();
obj.innerHTML = error;
return false
}
return true;
}
function validatePwd1() /* password & retype-password verification */
{
var obj = document.getElementById('pwd1error');
var invalid = ' ';
var pw1 = document.getElementById('pass1').value;
var pw2 = document.getElementById('pass2').value;
var error = false;
obj.innerHTML = '';
if (pw1.length < 1)
{
error = 'Enter your new password';
}
else if (pw1.indexOf(invalid) > -1)
{
error = 'You need a password';
}
if (error)
{
document.getElementById('pass1').focus();
obj.innerHTML = error;
return false
}
if (pw1 != pw2)
{
obj.innerHTML = 'passwords are not the same, try to re-enter your password';
return false;
}
return true;
}
function validate()
{
var form = document.forms['register'];
var ary = [checkName, validatePwd, validatePwd1];
var rtn = true;
var z0 = 0;
for (var z0 = 0; z0 < ary.length; z0++)
{
if (!ary[z0](form))
{
rtn = false;
}
}
return rtn;
}
</script>
Form
<form name="register" method="post" action="#" onSubmit="return validate()">
<table border="0">
<tr>
<td colspan="2">
<h1 class="title">Password Change Form</h1>
</td>
</tr>
<tr>
<td><span class="style20">Username </span></td>
<td><input name="username" id="username" type="text"></td>
<td><span id="usernameerror" class="style20"> </span></td>
</tr>
<tr>
<td><span class="style20">Old Password</span></td>
<td><input name="pass" id="pass" type="password"></td>
<td><span id="pwderror" class="style20"> </span></td>
</tr>
<tr>
<td><span class="style20">New Password</span></td>
<td><input name="pass1" id="pass1" type="password"></td>
<td><span id="pwd1error" class="style20"> </span></td>
</tr>
<tr>
<td><span class="style20">Repeat New Password</span></td>
<td><input name="pass2" id="pass2" type="password"></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="Submit" value="Submit">
<input type="reset" name="reset" value="Reset"></td>
</tr>
</table>
</form>