Prefilled the form data from the another page's input - javascript

I am trying to pass some data from one web page to another
while clicking on the button.
Blade Page:
<div class="container">
<div class="row">
<div class="col-md-7 info" style="padding-right: 35px;padding-top: 40px" >
<h1 style="text-align: right;margin-bottom: 0px; font-style:italic;font-size:28px">"Wǒ bù zhīdào cóng nǎlǐ kāishǐ, píngtái bāng wǒ zhǎodàole zhīchí. Wǒ zhēn de hěn xǐhuān tāmen rúhé gēnjù wǒ de yùsuàn wèi wǒ tígōng duō zhǒng xuǎnzé bìng bāngzhù wǒ pínggū tāmen.</h1>
<br>
<p style="text-align:right; font-weight:bold; font-size:16px">Alvin R., Entrepreneur</p>
</div>
<div class="col-md-5" style="padding-left: 35px;">
<div class="card" style="border-radius: 20px !important;">
<div class="card-head" style="text-align: center;font-weight: bold;padding-top: 25px;">
<header style="font-size: 25px;color: #3f9ae5;">GET STARTED</header>
</div><!--end .card-head -->
<div class="card-body" style="font-weight: bold;font-size: 16px;padding-left: 30px;">
<div class="form" style="padding-left: 15px;padding-right: 15px;">
<div class="row">
<div class="col-md-12">
<div class="form-group" style="margin-bottom: 20px;">
<select style="margin-top: 15px;font-size: 16px;" id="aops" class="form-control select2-list" name="areas">
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12" id="req_options">
<div class="form-group">
<select style="margin-top: 15px;color: grey;font-size: 16px;" id="request_type" class="form-control select2-list" name="request_types" >
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<input type="text" placeholder="Title " style="margin-top: 10px;padding-left: 10px;font-size: 16px;" class="form-control" name="title" id="title">
</div>
</div>
</div>
</div>
<button class="btn btn-theme effect standard btn-sm" id="post_request" style="background-color: #3f9ae5 !important;border-style: none;color:#ffffff;font-weight:bold;width: 100%;font-size: 16px">Post a Request</button>
<p style="font-size: 13px;padding-top: 24px;text-align: center;">By signing up you agree to the <u> terms of use</u> and <u>privacy policy</u></p>
</div><!--end .card-body -->
</div><!--end .card -->
</div>
</div>
</div>
I have one simple template page where user can select two dependent drop-downs, AreaOfPractice and RequestsType and the other 'title' text filled, as user selects on the get started he will redirect to the new page where he will the requests filling form with 5-6 fields wherein 3 fields would be prefilled with user's input from the previous page.
I have tried to do it with jQuery & Ajax.
$.ajax({
url:"getAops",
type: "POST",
data:{_token:csrf_token},
success:function (result) {
var options_grp = "";
options_grp = "<option></option>";
for(i=0;i<result.length;i++){
options_grp = options_grp + "<option value='" +result[i].name+"_"+result[i].id+"'>"+result[i].name+"</option>"
}
$(options_grp).appendTo('#aops');
$('#aops').select2({
placeholder: "Select Category *"
});
}
});
$('#aops').on('change',function () {
$.ajax({
url:"getRequestTypes",
type: "POST",
data:{_token:csrf_token,aop_id:$('#aops').val().split('_')[1]},
success:function (result) {
$('#request_type').empty().trigger('change');
$('#req_options').css('display','block');
var options = "<option></option>";
for (var i = 0;i<result.length;i++){
options = options + "<option value='" +result[i].name+"_"+result[i].id+"'>"+result[i].name+"</option>";
}
$(options).appendTo('#request_type');
$('#request_type').select2({
placeholder: "Select Request Type *"
})
}
});
});
$('#post_request').on('click', function () {
var data = new FormData();
if($('#aops').select2('data') != null){
aop = $('#aops').select('data').text;
}
if($('#request_type').select('data') != null){
request_type = $('#request_type').select2('data').text;
}
data.append("aop", $('#aops').val());
data.append("request_type",$('#request_type').val());
data.append("title",title);
if(aop == "" || request_type == "" || title == "" ){
show_notification("error","Please fill all required fields");
return false;
}else {
$.ajax({
url: "createNewRequest",
type: "POST",
async: false,
data: data,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function () {
$('#aops').html(aop);
$('#request_type').html(request_type);
$('#title').val(title);
return true;
},
contentType: false,
processData: false
});
}
});

Here is a basic example to the technique.
You can save many fields by making an object like {name-field:name-data,x-field:x-data} and so on. You can retrieve this on other page and set it to the form inputs.
$("#setbutton").click(()=>localStorage.setItem("form-data",$("#set").val()))
$("#getbutton").click(()=>{
var data=localStorage.getItem("form-data")
$("#get").val(data);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="set"/>
<button id="setbutton">Set</button>
<br><br><br>
<input type="text" id="get"/>
<button id="getbutton">Get</button>

Related

Form is being Submitted every time The button is clicked

I am having a form in which I am saving 2 files and a field. The problem I am facing is every time I click the submit button the form is getting submitted. Although The text field is resetting, the file still consists the value of previous record. How to reset the file here once the form is submitted.
HTML
<form id="formOrder" autocomplete="off" method="POST" enctype="multipart/form-data">
<div class="row row-sm">
<div class="col-lg-8">
<div class="row row-sm">
<div class="col-lg-6">
<div class="input-group mb-4">
<input aria-label="Invoice ID" id="invoiceId" name="invoiceId" class="form-control" placeholder="Invoice ID" type="text">
<span class="text-danger"></span>
</div>
</div>
</div>
</div>
<div class="col-lg-4">
<div>
<div class="input-group mb-3">
<div class="input-group file-browser">
<input id="imageLabel" type="text" class="form-control browse-file" placeholder="Select Order Image" readonly>
<label class="input-group-btn">
<span class="btn btn-default">
Browse <input type="file" name="image[]" id="orderImage" style="display: none;" multiple>
</span>
</label>
</div>
<div class="orderImagePreview">
</div>
</div>
</div>
</div>
</div>
<div class="form-group mb-0 mt-3 justify-content-end">
<div>
<input type="submit" id="_add" name="_add" class="btn btn-primary btn-size" value="Add"/>
</div>
</div>
</form>
JQUERY
// BUTTON CLICK SUBMISSION
$(document).ready(function(e){
$("#_add").click(function(){
$("#formOrder").on('submit', function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: '../order/add.php',
data: new FormData(this),
dataType: 'json',
contentType: false,
cache: false,
processData:false,
async: false,
autoUpload: false,
success: function(response){
$('.statusMsg').html('');
if(response.status == 1){
$('#formOrder')[0].reset(); //FORM TO RESET AFTER SUBMISSION
$('.statusMsg').html('<p class="alert alert-success">'+response.message+'</p>');
alert('received');
$('.orderImagePreview').empty();
document.getElementById('#orderImage').value= null; //TO MAKE THE IMAGE LABEL EMPTY
}else{
$('.statusMsg').html(alert(response.message));
}
$('#formOrder').css("opacity","");
$(".submit").removeAttr("disabled");
}
});
});
});
});
// Multiple images preview in browser
$(function() {
var imagesPreview = function(input, placeToInsertImagePreview) {
if (input.files) {
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
$($.parseHTML('<img>')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
}
reader.readAsDataURL(input.files[i]);
}
}
};
$('#orderImage').on('change', function() {
imagesPreview(this, 'div.orderImagePreview');
$( 'div.orderImagePreview' ).empty();
});
});
$('#orderImage').on("change", function(){
var input = document.getElementById ("imageLabel");
var imageCount = $(this)[0].files.length;
if(imageCount > 0){
input.placeholder = imageCount+" Image Attached";
}else{
input.placeholder = "Select Order Image";
}
});
Where I am making the mistake? The debugging should be to reset the form with file or the method of form submission? Thanks in Advance.
$("#_add").click(function(){
$("#formOrder").on('submit', function(e){
Just create a submit handler when the document loads.
Don't add it when the button is clicked.

AntiforgeryToken generation from using #Ajax.BeginForm()

I have an issue in generating anti-forgery token manually inside ajax methods. So my question If I used ajax.beginform(), does it generate a token like the #html.beginform? If so, how can I use it with my ajax methods?
Kindly ignore the long code in the view. My main concern is with the ajax methods. I posted it to show you the view in case of the suggestion of using the beginForm().
#*#Html.AntiForgeryToken()*#
<hr />
<div class="row">
<div class="col-lg-6">
<label><strong>Month:</strong></label>
</div>
<div class="col-lg-6">
<label>#manning_HQ.Issue_Date</label>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<label><strong>Count:</strong></label>
</div>
<div class="col-lg-6">
<label>#manning_HQ.Count</label>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<label><strong>Location:</strong></label>
</div>
<div class="col-lg-6">
<label>#manning_HQ.Location_Name</label>
</div>
</div>
<hr />
<div class="col-lg-4">
<label>Recruitment Status :</label>
</div>
<div class="col-lg-3">
<select id="recruitment_Status">
<option value="0">
Choose Status
</option>
#foreach (TBL_Recruitment_Status rec in recruitment_Status)
{
<option value="#rec.Rec_Status_ID">
#rec.Status_Name
</option>
}
</select>
</div>
<div class="row">
<div class="col-lg-12">
<label><strong>Issue staff requisition:</strong></label>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<input type="radio" name="Decision" id="_123" value="Accepted" />
Accepted
</div>
<div class="col-lg-6">
<input type="radio" name="Decision" id="_456" value="Rejected" />
Rejected
</div>
</div>
<hr />
<div class="row" id="RejComment" hidden>
<div class="col-lg-6">
<label>Rejected Comment :</label>
</div>
<div class="col-lg-3">
<textarea id="RetainedComment"></textarea>
</div>
</div>
<br />
<div class="modal-footer" id="Save_Dicision" hidden>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" onclick="saveDecision(#manning_HQ.Issue_Staff_ID)">Save</button>
</div>
<script>
var DecesionCheck = false;
var rejected = false;
var reason = false;
$(document).ready(function () {
$('input[type=radio][name=Decision]').change(function () {
if ($("input[name='Decision']:checked").val() == 'Accepted') {
$('#RejComment').hide();
$('#Save_Dicision').show();
rejected = true;
}
if ($("input[name='Decision']:checked").val() == 'Rejected') {
$('#RejComment').show();
$('#Save_Dicision').show();
rejected = true;
}
});
});
function saveDecision(ID) {
var Decsion = $('input[name=Decision]:checked').val();
var Reason = $('#recruitment_Status').val();
//var token = $("[name='__RequestVerificationToken']").val();
if (Decsion == "#_123") {
if (DecesionCheck == true) {
var Decsion = $('input[name=Decision]:checked').val();
var optionalComment = $('#OptionalComment').val();
$.ajax({
type: 'POST',
url: '/Staff_Requisition_HQ/Recruitment_Actions',
data: {
// __RequestVerificationToken: token,
Issue_Staff_ID: ID,
Rec_Status_ID: Reason,
OpComment: RetainedComment,
RecDecison: Decsion,
},
success: function (result) {
$('#DescionDetailsPOPUP').modal('hide');
location.reload();
},
fail: function (xhr, textStatus, errorThrown) {
alert('request failed');
}
});
}
}
else {
var Decsion = $('input[name=Decision]:checked').val();
var RetainedComment = $('#RetainedComment').val();
$.ajax({
type: 'POST',
url: '/Staff_Requisition_HQ/Recruitment_Actions',
data: {
//__RequestVerificationToken: token,
Issue_Staff_ID: ID,
Rec_Status_ID: Reason,
Comment: RetainedComment,
RecDecison: Decsion,
},
success: function (result) {
$('#DescionDetailsPOPUP').modal('hide');
location.reload();
},
fail: function (xhr, textStatus, errorThrown) {
alert('request failed');
}
});
}
}
</script>
Here's an example of Ajax.BeginForm from one of my views:
<!-- FORM Atributo -->
#using (Ajax.BeginForm(accionFormulario, "Atributos", new AjaxOptions() { OnSuccess = "onSuccessCreate" }, new { #id = "frmCreate" }))
{
#Html.AntiForgeryToken()
#Html.HiddenFor(model => model.AtributoId)
#Html.HiddenFor(model => model.EmpresaId)
<div class="modal-body">
<div class="row">
// the form inputs ....
</div>
</div>
<div class="modal-footer">
<button class="btn btn-secondary mx-1" type="button" data-dismiss="modal" aria-label="Close">#Global.Cancelar</button>
<button class="btn btn-primary" type="submit"><strong>#Global.Guardar</strong></button>
</div>
}
This generates the AntiForgeryToken as expected:
You can capture it with javascript as you were doing in your view.

Fill in radio input with database data

When I query the form returns the input radio filled with the data of the database, as shown:
<input type="radio" id="Estado" name="Estado" value="Pendente" ' . ( ($row6["Estado"]=='Pendente') ? 'checked' : '' ) .' readonly="true"> Pendente <input type="radio" id="Estado" name="Estado" value="Concluído" ' . ( ($row6["Estado"]=='Concluído') ? 'checked' : '' ) .' readonly="true"> Concluído
I also show in the completed image:
But when I click the edit button it changes the filled input radio and should not, because it no longer fills according to the data of the database, as I show in the image:
script:
$(document).on('click', '.edit_data6', function(){
var employee_id6 = $(this).attr("Id");
$.ajax({
url:"./fetch26",
method:"POST",
data:{employee_id6:employee_id6},
dataType:"json",
success:function(data){
$('#data6').val(data.data6);
$('#Colaborador6').val(data.Colaborador6);
$('#Observacao6').val(data.Observacao6);
$('#Estado1').prop("checked", data.Estado);
$('#Conclusao').val(data.Conclusao);
$('#employee_id6').val(data.Id6);
$('#insert6').val("Gravar");
$('#exampleModal6').modal('show');
}
});
});
$('#insert_form6').on("submit", function(event){
event.preventDefault();
if($('#Colaborador6').val() == "")
{
alert("Colaborador é necessário");
}
else
{
$.ajax({
url:".conexao26",
method:"POST",
data:$('#insert_form6').serialize()
,
beforeSend:function(){
$('#insert6').val("Inserting");
},
success:function(data){
$('#insert_form6')[0].reset();
$('#exampleModal6').modal('hide');
$('#employee_table').html(data);
location.reload("exampleModal6");
}
});
}
});
HTML:
<form method="post" id="insert_form6">
<div class="col-md-4 col-xs-4">
<div class="form-group">
<h6><label for="Data-name" class="col-form-label">Data</label></h6>
<h6><input type="date" name="data6" id="data6" value="<?php echo date("Y-m-d");?>"></h6>
</div>
</div>
<div class="col-md-4 col-xs-4">
<div class="form-group">
<h6><label for="Colaborador-text" class="col-form-label">Colaborador</label></h6>
<h6><select style="width:150px" name="Colaborador6" id="Colaborador6" required>
<option></option>
<?php
$sql = "SELECT Funcionario FROM centrodb.InfoLuvas WHERE Ativo = '1' AND Funcao = 'Limpeza' AND Valencia = 'LAR'";
$qr = mysqli_query($conn, $sql);
while($ln = mysqli_fetch_assoc($qr)){
echo '<option value="'.$ln['Funcionario'].'">'.$ln['Funcionario'].'</option>';
}
?>
</select></h6>
</div>
</div>
<div class="row">
</div>
<div class="col-md-6 col-xs-6">
<div class="form-group">
<h6><label for="Observacao-name" class="col-form-label">Tarefa Pendente</label></h6>
<textarea type="text" id="Observacao6" name="Observacao6" class="form-control"></textarea>
</div>
</div>
<div class="col-md-6 col-xs-6">
<div class="form-group">
<h6><label for="Observacao-name" class="col-form-label">Estado</label></h6>
<div style="clear:both;"></div>
<h6><input type="radio" id="Estado1" name="Estado" value="Pendente"> Pendente <input type="radio" id="Estado1" name="Estado" value="Concluido"> Concluído</h6>
</div>
</div>
<div class="row">
</div>
<div class="col-md-6 col-xs-6">
<div class="disabled form-group">
<h6><label for="Observacao-name" class="col-form-label">Conclusão</label></h6>
<textarea type="text" id="Conclusao" name="Conclusao" class="form-control"></textarea>
</div>
</div>
<div class="col-md-2 col-xs-2">
<div class="form-group">
<h6><input type="hidden" name="Nome6" id="Nome6" value="Ana Ribeiro" readonly="true"></h6>
</div>
</div>
<div class="col-md-2 col-xs-2">
<div class="form-group">
<h6><input type="hidden" name="NomeConc" id="NomeConc" value="Ana Ribeiro" readonly="true"></h6>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Sair</button>
<input type="hidden" name="employee_id6" id="employee_id6" />
<input type="submit" name="insert6" id="insert6" value="Registo" data-toggle="modal" class="btn btn-success" />
</div>
</form>
I'm trying these ways but I still do not solve the problem:
1st form:
var tipo_conta = $('.tipo_conta').val(data.Estado);
if(tipo_conta == 'Pendente'){
$('#Estado1').prop('checked' , true);
}else{
$('#Estado2').prop('checked' ,true);
}
2st form:
var radios = document.getElementsByName("Estado");
if (radios.value == "Pendente") {
radios.checked = true;
}else{
radios.checked = true;
}
Can anyone help?
I found the issue inside the HTML file. As #daddygames suggested you have used the same ID in both Radio button. see below
<h6>
<input type="radio" id="Estado1" name="Estado" value="Pendente"> Pendente
<input type="radio" id="Estado1" name="Estado" value="Concluido"> Concluído
</h6>
An ID must be unique. Update the ID and make it unique. Then change the code in .ajax script according to your need. This will help you.
First I created the variable lis to receive the value that the radio input receives from the database:
var lis = $("#Estado").val();
Then inside the data function I created another variable with the value that the radio input receives from the function:
var teste = data.Estado;
and finally I check with if:
if(lis == teste){
$('#Estado').prop('checked' , true);
}else{
$('#Estado1').prop('checked' ,true);
}
Full Code:
$(document).on('click', '.edit_data6', function(){
var employee_id6 = $(this).attr("Id");
var lis = $("#Estado").val();
$.ajax({
url:"./fetch26",
method:"POST",
data:{employee_id6:employee_id6},
dataType:"json",
success:function(data){
var teste = data.Estado;
$('#data6').val(data.data6);
$('#Colaborador6').val(data.Colaborador6);
$('#Observacao6').val(data.Observacao6);
if(lis == teste){
$('#Estado').prop('checked' , true);
}else{
$('#Estado1').prop('checked' ,true);
}
$('#Conclusao').val(data.Conclusao);
$('#employee_id6').val(data.Id6);
$('#insert6').val("Gravar");
$('#exampleModal6').modal('show');
}
});
});

Show loading image while my controller execute a function

need to show an image while my function "Mailcontroller/sendMail" is working sending an email. I passed values to this function from my view by a submit button in a form. I had try with other examples that I saw here, but I can't get what I need.
My view:
<div class="container" style="margin-right: 100px;">
<div class="row">
<div class="col-md-9 col-md-offset-3">
<form class="form-horizontal" enctype='multipart/form-data' method="POST" action="<?=base_url();?>Cpersona/sendMail">
<fieldset>
<div class="form-group">
<div class="col-md-6">
<label style="font-size: 15px; margin-left: 215px;">Destinatarios</label><br />
<input type="button" name="agregardes" id="agregardes" onclick="llenarDestino();correos();" style="font-size: 15px; margin-left: 215px;" value="Agregar Destinatarios">
<input style="margin-left: 215px;" id="email" name="email" type="text" class="form-control" required>
<label style="font-size: 15px; margin-left: 215px;">Asunto</label><br />
<input style="margin-left: 215px;" type="text" class="form-control" name="asunto" id="asunto">
<label style="font-size: 15px; margin-left: 215px;">Mensaje</label><br />
</div>
<div class="col-md-9" style="float: right;">
<textarea id="editor" name="mensaje"></textarea>
</div>
</div>
<section>
<div style="margin-left: 215px;">
<p id="msg"></p>
<input type="file" id="file" name="file" />
</div>
</section>
<div>
<br />
<input style="margin-left: 215px;" class="btn btn-primary" type="submit" id="enviar" name="enviar" value="Enviar">
</div>
</fieldset>
</form>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#enviar').click(function(){
//Añadimos la imagen de carga en el contenedor
$('#content').html('<div><img src="../assets/images/loading.gif"/></div>');
var page = $(this).attr('data');
var dataString = 'page='+page;
$.ajax({
type: "GET",
url: "http://localhost/empresa/Cpersona/sendMail",
data: dataString,
success: function(data) {
//Cargamos finalmente el contenido deseado
$('#content').fadeIn(1000).html(data);
}
});
});
});
</script>
An extract of my Controller:
public function sendMail{
$data = array(
'id_usuario' => $usuario,
'fecha' => $fecha,
'id' => $cliente
);
$this->Modelo_datos->historial($data);
$this->email->set_newline("\r\n");
$this->email->from('correopruebas#consultora.cl');
$this->email->to($value);
$this->email->subject($asunto);
$this->email->message($enviar);
//$path = set_realpath('./uploads/');
//$adjunto = $path.$archivo;
if($this->email->send())
{
$this->load->helper("file");
delete_files('./uploads/');
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Correo Enviado!!')
window.location.href='verLista';
</SCRIPT>");
}
else
{
show_error($this->email->print_debugger());
$this->load->helper("file");
delete_files('./uploads/');
}
}
}
first add image(that you want to be displayed) with id loader and make it hidden by using style="display:none";
loader = document.querySelector("#loader");
function sendMail() {
loader.style.display = "block";
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
loader.style.display="none";
// some thing here when email is sent
}
};
xhttp.open("GET", "your_send_mail_file.php?send=true", true);
xhttp.send();
}
and in your_send_mail_file.php
<?php
if (isset($_GET["send"]) && $_GET["send"] === "true") {
$test = new your_class(); // that_contain_the_sendMail function;
$test->sendMail();
}

Populate dynamical form with json

I am trying to populate an html form using js, and j query and i have encountered a problem.
The form is growing according to the user request, the user need to fill 4 different inputs and if he wants he can click on a button and add another 4 inputs.
here is the form:
<form action="#main" method="post" id="exercise-form">
<div data-role="header" class="header" data-theme="a" data-position="fixed">
<a class="ui-btn-right" data-icon="check" onclick="$('form#exercise-form').trigger('submit');
resetExerciseForm();" data-iconpos="notext"></a>
<h1 class="text">Add a Workout</h1>
<a href="#main" data-role="button" class="ui-btn-left" data-icon="home" data-iconpos="notext" onclick="$('form#exercise-form').trigger('reset');
resetExerciseForm();"></a>
</div>
<div data-role="fieldcontain" class="ui-field-contain ui-body ui-br">
<label for="date" class="text">Workout Date:</label>
<input type="date" name="date" value="" class="ui-input-text ui-body-c ui-corner-all ui-shadow-inset form-element serializable" style="color: white; font-family:'Ariel'; text-shadow:none;">
</div>
<br>
<div id="exercise-template" style="display: none;">
<!-- Exercise name -->
<div data-role="fieldcontain">
<label for="ex-name" class="text">Exercise Name:</label>
<input class="form-element serializable" type="text" name="ex-name-1" value="" style="color: white; font-family:'Ariel'; text-shadow:none;"/>
</div>
<div class="ui-grid-b">
<!-- Number of Sets -->
<div class="ui-block-c">
<div data-role="fieldcontain">
<label for="set-number" class="text">Sets:</label>
<input class="form-element serializable" type="number" name="set-number-1" value="" style="color: white; font-family:'Ariel'; text-shadow:none;"/>
</div>
</div>
<!-- Number of Repetitions -->
<div class="ui-block-c">
<div data-role="fieldcontain">
<label for="rpt-number" class="text">Repetitions:</label>
<input class="form-element serializable" type="number" name="rpt-number-1" value="" style="color: white; font-family:'Ariel'; text-shadow:none;"/>
</div>
</div>
<!-- Weight -->
<div class="ui-block-c">
<div data-role="fieldcontain">
<label for="weight" class="text">Weight:</label>
<input class="form-element serializable" type="number" name="weight-1" value="" style="color: white; font-family:'Ariel'; text-shadow:none;"/>
</div>
</div>
</div>
<br>
</div>
<label for="text-area" class="text">Json:</label>
<span id="text-area" style="color: white; font-family:'Ariel'; text-shadow:none;"></span>
</form>
When the user want to add one more exercise the next java script is running:
function addExerciseForm() {
var oldId = exerciseId;
var newId = ++exerciseId;
document.getElementsByName('ex-name' + oldId).name = 'ex-name' + newId;
document.getElementsByName('set-number' + oldId).name = 'set-number' + newId;
document.getElementsByName('rpt-number' + oldId).name = 'rpt-number' + newId;
document.getElementsByName('weight' + oldId).name = 'weight' + newId;
var clonable = document.getElementById('exercise-template');
var clone = clonable.cloneNode(true); //true for deep clone
clonable.id = "exercise" + newId;
clone.id = 'exercise-template';
clonable.style.display = 'initial';
// var addButton = document.getElementById('add-exercise-button');
clonable.parentNode.appendChild(clone);
clonable.removedNode();
clone.parentNode.appendChild(clonable);
}
As u can see the hole div with the id exercise-template is being cloned with different id that is increased by 1.
When i clone the div i am trying to change the name of so when i populate it from a json file i wont have more then one label with the same name.
The problem is that when i look at the DOM after cloning the div i can see that the name hasn't change while if i use chrome debug mode i can see that the line:
document.getElementsByName('ex-name' + oldId).name = 'ex-name' + newId;
actually giving me the wanted element. But the populate script cant find the name of the new element.
here is the populate script:
function populateExerciseForm() {
$.ajax({
dataType: 'json',
type: 'GET',
url: 'json/exercise.json',
xhrFields: {
withCredentials: true
},
success: function (response, status) {
console.log(response, status);
if (status === "success") {
// we expect a response in a JSON format
// response = JSON.parse(response);
$('#exercise-form').populate(response);
}
}
});
}
Anyone know what is the problem?
or for example how can i take the next json and let the first 4 values inside the first 4 inputs and so on..?
json example:
{
"ex-name-1": "abc",
"set-number-1": 2,
"rpt-number-1": 3,
"weight-1": 20,
"ex-name-1": "efg",
"set-number-1": 4,
"rpt-number-1": 4,
"weight-1": 123
}
I hope my problem is clear.
Thanks ahead!!

Categories

Resources