I am working on a piece of code in which I want to generate span and textarea elements based on the number of JSON key:value pairs.
This is my html:
<div class="modal fade" id="addPropertyModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Add Property</h4>
</div>
<div class="modal-body">
<div class="input-group input-group-lg">
<span class="input-group-addon">Name</span>
<input type="text" id="newProperty" name="newProperty" class="form-control" placeholder="name">
</div>
<br/>
**<div class="input-group input-group-lg">
<span class="input-group-addon">Value</span>
<textarea id="newValue" name="newValue" class="form-control" placeholder="value" style="resize:vertical;" ></textarea>
</div>**
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" id="savePropertyBtn" name="action" value="Save Property" class="btn btn-primary"/>
<input type="submit" id="updatePropertyBtn" name="action" value="Update Property" class="btn btn-primary"/>
</div>
</div>
</div>
</div>
</div>
The script which loads the newValue is this:
$(".href-select").click(function() {
var propName = $(this).text();
var propVal = $(this).attr('itemprop');
var json = JSON.parse(propVal, 'UTF-8');
var count = 0;
for (i in json) {
console.log(json[i]);
count++;
}
console.log(count);
$("#newProperty").attr('readonly', true);
$("#newProperty").val(propName);
$("#newValue").val(propVal);
$("#savePropertyBtn").hide();
$("#updatePropertyBtn").
});
I have modded the script to get the individual values from the JSON.
My idea is : to increment the count as I read the JSON values and then use this to add count number of span & textarea elements in the html through iteration. Also I want to add the count in the html and hide it so that I can get the count in the request object as well ( I will be creating a map with the number of values ).
Please help me in achieving my idea.
EDIT : This is what is expected if the JSON contains two pairs.
<div class="input-group input-group-lg">
<span class="input-group-addon">Value</span>
<textarea id="newValue" name="newValue" class="form-control" placeholder="value" style="resize:vertical;" ></textarea>
<span class="input-group-addon">Value</span>
<textarea id="newValue" name="newValue" class="form-control" placeholder="value" style="resize:vertical;" ></textarea>
</div>
EDIT 2: This is how the dialog box looks right now :
The value textbox contains the JSON. Now I want the textbox to look like this:
Name: [test222]
Host: [DS01ATA]
Port: [ 22 ]
You have to get the div first, then call the append function on it. For example, if you did $(".input-group"), that would give you a list of all html elements with a class of input-group (notice the period before the class name in the selector). Remember, classes aren't guaranteed unique, so my example is only unique if you only use that class once. Once you have the desired element, you can manipulate that element. In this case, you want to add an HTML element to the div.
$(".input-group").append("<span>Sample html string</span>");
References:
Docs for append: http://api.jquery.com/append/
CSS selector "playground" (with documentation): http://codylindley.com/jqueryselectors/
To copy - paste a div using jQuery
function copyDiv(divId) {
var content = $(divId).html();
var newdiv = $('<div>');
newdiv.html(content);
$(divId).after(newdiv);
return newdiv;
}
Calling copyDiv('#mydiv') will create a div with same content below #mydiv.
jQuery .clone() may also be useful here.
For your case, this function can be called inside your loop
for (i in json) {
var newdiv = copyDiv('#form-div-id');
... // add values to new div like 'i' and json[i]
}
Related
I'm trying to create a way to add entries to my form so that the user can choose how many he wants, but I can't get the remove part working.
JavaScript
var i = 1;
var divContent = document.getElementById('formulario');
//Click to add a field
function cria() {
//This add a HTML Inputs and divs who the ID is variable how the 'i' is increasedf
document.getElementById('formulario').innerHTML += '<div class="mb-1 col-3" id="div'+i+'"><label for="nomeTx0" class="form-label">Nome</label><input type="text" class="form-control" id="nomeTx'+i+'" name="nomeTx'+i+'" required></div><div class="mb-1 col-3" id="div2'+i+'"><label for="taxa'+i+'" class="form-label">Valor</label><input type="float" class="form-control" id="taxa'+i+'" name="taxa'+i+'" required></div>- Remover campo';
i++;
}
function remove(div1, div2){
var div = document.getElementById(div1);
var div2 = document.getElementById(div2);
div.remove();
div2.remove();
i--;
}
And now the HTML
<form>
<h4 class="card-tittle text-center">Taxas</h4>
<div id="formulario" class="form row align-items-start">
<div class="mb-1 col-3" id="0">
<label for="nomeTx0" class="form-label">Nome</label>
<input type="text" class="form-control" id="nomeTx0" name="nomeTx0" required>
</div>
<div class="mb-1 col-3" id="0">
<label for="taxa0" class="form-label">Valor</label>
<input type="float" class="form-control" id="taxa0" name="taxa0" required>
</div>
</div>
+ adicionar campo
<div class="mb-1 col-lg-12" style="text-align: center;">
<button class="btn btn-primary col-5" id="Enviar" type="submit" text="Enviar">Adicionar Taxas</button>
</div>
</form>
ID="taxa"+i but when I call the remove(); error is printed to me saing the variable is null.
This is really not the right approach in the first place.
Your fundamental problem is that you are relying on ids to know what element(s) to add and remove and this is leading you to concatenate an id onto dynamically created elements, made from long strings with variables concatenated into them. In reality, you should avoid ids whenever possible as they make your code very brittle and don't scale well.
This is a perfect use for the HTML <template> element. As you can see from the re-worked code below, all ids have been removed - - you don't need them. Additionally, instead of long strings with a variable concatenated into it, you just need to copy/clone the template whenever you need one. Then, you can use "event delegation" and smartly organized HTML to just set up a single click event on a master wrapper element, where the actual element that was clicked (the event.target) can be checked. If it was a remove button, then just remove the entire wrapper that is the nearest ancestor to the remove button that was clicked.
You can now add and remove as many items as you like with no need for an id or counting variables!
// Get a reference to the template, outer div and the add "button"
const template = document.querySelector("template");
const wrapper = document.querySelector(".wrapper");
const add = document.querySelector(".add");
// Set up the add event in Javascript, not with inline HTML
add.addEventListener("click", function(event){
var clone = template.content.cloneNode(true); // Clone the template
wrapper.appendChild(clone);
});
// Set up a wrapper level click event that any clicks within it will bubble up to
wrapper.addEventListener("click", function(event){
// Test to see if it was remove "button" that was clicked
if(event.target.classList.contains("remove")){
// Just remove the closest ancestor div that holds that particular group
// and remove it.
event.target.closest("div.templateWrapper").remove();
}
});
.mb-1.col-lg-12 {
text-align:center;
}
.mb-1.col-3 {
margin:2px;
}
.add, .remove {
cursor:pointer;
color:blue;
}
.labelName { display:inline-block; width:3em; }
/* This is just to better see the groups */
.templateWrapper, .form {
background-color:aliceblue;
padding:5px;
margin:8px;
}
<!-- This will not initially be shown on the page.
It will be used to copy from when/if needed. -->
<template>
<div class="templateWrapper">
<div class="mb-1 col-3">
<label class="form-label"><span class="labelName">Nome</span>
<input type="text" class="form-control" name="nomeTx" required>
</label>
</div>
<div class="mb-1 col-3">
<label class="form-label"><span class="labelName">Valor</span>
<!-- An input does not have a type=float -->
<input class="form-control" name="taxa" required>
</label>
</div>
<span class="remove">- Remover campo</span>
</div>
</template>
<form>
<h4 class="card-tittle text-center">Taxas</h4>
<!-- Hyperlinks are for navigation, not JavaScript click hooks. Any visible element
supports a click event. Use span and div for generic clickable inline or block
elements that need to have click event handlers. -->
<span class="add">+ adicionar campo</span>
<div class="wrapper">
<div class="form row align-items-start">
<div class="mb-1 col-3">
<label class="form-label"><span class="labelName">Nome</span>
<input type="text" class="form-control" name="nomeTx0" required>
</label>
</div>
<div class="mb-1 col-3">
<label class="form-label"><span class="labelName">Valor</span>
<input type="float" class="form-control" name="taxa0" required>
</label>
</div>
</div>
</div>
<div class="mb-1 col-lg-12">
<!-- A button does not have a "text" attribute -->
<button class="btn btn-primary col-5" type="submit">Adicionar Taxas</button>
</div>
</form>
You would like to pass the ids of the html elements to function remove , instead you pass something else.
Try this:
function remove(d1, d2){
//what are passing to function... id , or something else ?
console.log(d1,d2);
// now I force the arguments passed to function to a valid value id for test
var a = document.getElementById('div1'); // id is div1
var b = document.getElementById('div21'); // id is div21
//Ask to parentNode to remove his child
a.parentNode.removeChild(a);
b.parentNode.removeChild(b);
i--;
}
The problem in your code is that you don't pass a string to the remove function but instead you pass the whole element. That is why document.getElementById can't find anything because it expects a string as a parameter. I refactored you code a bit and also when removing the fields the link - Remover campo stayed and was not deleted. I fixed that as well by passing a third argument to the remove function.
var i = 1;
var divContent = document.getElementById('formulario');
//Click to add a field
function cria() {
//This add a HTML Inputs and divs who the ID is variable how the 'i' is increasedf
document.getElementById('formulario').innerHTML += '<div class="mb-1 col-3" id="div'+i+'"><label for="nomeTx0" class="form-label">Nome</label><input type="text" class="form-control" id="nomeTx'+i+'" name="nomeTx'+i+'" required></div><div class="mb-1 col-3" id="div2'+i+'"><label for="taxa'+i+'" class="form-label">Valor</label><input type="float" class="form-control" id="taxa'+i+'" name="taxa'+i+'" required></div>- Remover campo';
i++;
}
function remove(div1, div2, link){
var div = document.getElementById(div1);
var div2 = document.getElementById(div2);
var link = document.getElementById(link);
divContent.removeChild(div);
divContent.removeChild(div2);
divContent.removeChild(link)
i--;
}
The easiest way to do your code working it change your function "cria". (it's not the best option)
You miss ' '.
You have this.
onclick="remove(div'+i+',div2'+i+')"
You need this.
onclick="remove(\'div'+i+'\',\'div2'+i+'\')"
Javascript just doesn't understand that these parameters are strings.
And the full function "cria" after changes.
function cria() {
//This add a HTML Inputs and divs who the ID is variable how the 'i' is increasedf
document.getElementById('formulario').innerHTML += '<div class="mb-1 col-3" id="div'+i+'"><label for="nomeTx0" class="form-label">Nome</label><input type="text" class="form-control" id="nomeTx'+i+'" name="nomeTx'+i+'" required></div><div class="mb-1 col-3" id="div2'+i+'"><label for="taxa'+i+'" class="form-label">Valor</label><input type="float" class="form-control" id="taxa'+i+'" name="taxa'+i+'" required></div>- Remover campo';
i++;
}
Something strange bug is going on in my code. I want to use HTML template tag with jQuery, because all the rest of my code is jQuery, but I only found JavaScript examples with it. I tried to "translate" from JavaScript to jQuery, this is what I came up with.
$.getJSON( "../Controller/ControllerBookstore.php?show_books=true", function( data ) {
$.each( data, function( index, value ) {
// let clone = document.getElementById('table-template').content.cloneNode(true);
// clone.querySelector('#id').innerText = value.id;
// clone.querySelector('#author').innerText = value.author;
// clone.querySelector('#title').innerText = value.title;
// clone.querySelector('#isbn').innerText = value.isbn;
let clone = $("#table-template").clone(true);
$("#id",clone).text(value.id);
$("#author",clone).text(value.author);
$("#title",clone).text(value.title);
$("#isbn",clone).text(value.isbn);
//$(".container").append(clone);
$("#header").append(clone);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div id="myAlert" class="alert alert-success collapse">
<span id="alert-text"></span>
<a id="alert-close" class="close" href="#" aria-label="Close">×</a>
</div>
<div class="row" id="header">
<div class="col"><h5>ID</h5></div>
<div class="col"><h5>Author</h5></div>
<div class="col"><h5>Title</h5></div>
<div class="col"><h5>ISBN</h5></div>
<div class="col"><h5>Action</h5></div>
</div>
<template id="table-template">
<div class="row">
<div class="col" id="id"></div>
<div class="col" id="author"></div>
<div class="col" id="title"></div>
<div class="col" id="isbn"></div>
<div class="col buttons">
<button class='btn btn-info edit'>Edit</button>
<button class='btn btn-danger delete'>Delete</button>
</div>
</div>
</template>
<div class="row justify-content-center" >
<form action="" class="col-4">
<input id = "id-box" type="hidden" name="id">
<div class="form-group row">
<label class="col-4">Author</label>
<input id = "author-box" type="text" class="form-control col-8" name="author" placeholder="Enter the author of the book">
</div>
<div class="form-group row">
<label class="col-4">Title</label>
<input id = "title-box" type="text" class="form-control col-8" name="title" placeholder="Enter the title of the book">
</div>
<div class="form-group row">
<label class="col-4">ISBN</label>
<input id = "isbn-box" type="text" class="form-control col-8" name="isbn" placeholder="Enter the ISBN of the book">
</div>
<div class="form-group row">
<button id = "submit" type="submit" name="save" class="btn btn-primary col-12">Save</button>
</div>
</form>
</div>
</div>
For some reason the JavaScript code I commented out works, but it only appends "clone" to my ".container" correctly, on the next line below the form. However I want to attach it to my ".header", but it attaches next to the header, not below it. The jQuery code doesn't do anything, it doesn't attach my "clone" anywhere.
I hope I was clear. Could you please help me to find the reason of the bugs?
A few changes are needed:
The id value of the template has a hyphen which must be escaped in the selector. Two backslashes are needed in the string literal; the first is needed to actually get a backslash in the string. The remaining one will be interpreted by the selector.
Clone the row element within the template, not the template itself. However, jQuery will not know of a DOM within the template tag, so you could just take the HTML content instead of cloning, and then turn that into a jQuery object again (which produces the DOM for it).
Insert the clone just before the template
Code:
let clone = $($("#table\\-template").html()); // <--------
$("#id",clone).text(value.id);
$("#author",clone).text(value.author);
$("#title",clone).text(value.title);
$("#isbn",clone).text(value.isbn);
$("#table-template").before(clone); // <------
As others have commented, id attributes should have unique values, so your template content cannot have id properties (since it gets cloned). Use class attributes instead.
jQuery bug
Hello my friend. You are cloning the incorrect element, because your create a clone of template with the id #table-template. Please, make this change to your code:
...
let clone = $("#table-template").html();
...
The other thing, the cloned code appears next to #header and not below it because you are using a .row class. I propose to create a div below the #header, with the id="body" and append the new content inside:
...
// $("#header").append(clone);
-> $("#body").append(clone);
...
Thanks for the example.
But I don't change the id of the "collapse" div.
The rest of the objects are cloned normally.
<template id="facilities_template">
<div class="collapse">
<div class="form-check icon-check">
<input class="form-check-input" type="checkbox">
<label class="form-check-label font-14" id="facilities_name" ></label>
<i class="icon-check-1 far fa-square color-gray-dark font-20"></i>
<i class="icon-check-2 fa fa-check-square font-20 color-green-dark"></i>
</div>
<div class="mb-3"></div>
</div>
</template>
JavaScript:
let cloneFacility = $($('#facilities_template').html());
$('#facilities_name', cloneFacility).text(value.name);
$('#facilities_name', cloneFacility).attr('data-facility-id', value.id);
$('#collapse', cloneFacility).attr('id','collapse'+ value.id)
$('#facilities_template').before(cloneFacility);
$('#faсility_filter').append(cloneFacility);
I need to show an error message if No Radio Button is selected in the Model Form. I am getting Values into the radio form and now want to show a message that "Please select a Resume first" if no Resume is selected.
Following is the code for Model form in which I am showing the Radio Button:
<div class="modal fade" tabindex="-1" id="ResumeModal" role="dialog" ng-controller="topCtrl">
<div class="modal-dialog modal-sm">
<div class="modal-content ">
#using (Html.BeginForm("ApplyJob", "PostedJob", FormMethod.Post))
{
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
x
</button>
<h4 class="modal-title">Choose Your Resume</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12">
<input type="hidden" name="PostedJobId" id="PostedJobById" value="#Model.PostedJobId" />
<input type="hidden" name="CreatedBy" id="CreatedBy" value="#Model.CreatedBy" />
#foreach (var item in NurseOneStop.WebSite.Models.ApplicationSession.CurrentUser.NurseResumeList)
{
<div class="col-md-12 lstCard">
<input type="hidden" name="CheckedResumeId" id="CheckedResumeId" />
<input type="radio" name="RBCheckedResume" style="height: 15px; width: 18px;" onchange="CheckedResume(#item.ResumeId)" /> <span>#item.ResumeName</span>
</div>
}
</div>
<span style="color:Red">{{msg}}</span>
#*<label id="lblMessage" style="color:red"></label>*#
</div>
</div>
<div class="modal-footer">
<span style="color:Red">{{msg}}</span>
<button id="btnSubmitResume" type="submit" class="btn btn-primary pull-right" ng-click="userAlertResumeSubmit()">
Submit
</button>
</div>
}
</div>
</div>
</div>
Below is the code for JavaScript:
<script type="text/javascript">
$(document).ready(function () {
$("#btnShowModal").click(function (){
$("#ResumeModal").modal('show');
});
});
function CheckedResume(id) {
$('#CheckedResumeId').val(id);
console.log($('#CheckedResumeId').val());
};
</script>
This is how I did it on a website recently. Please note, you should swap out the 'UIKit.notification' for something else if you are not using UIKit already on the website.
$('.btnSubmitResume').submit(function(e){
if ($("input[name=RBCheckedResume]:checked").length === 0) {
e.preventDefault();
UIkit.notification({
message: 'Please check at least one box to continue',
status: 'primary',
pos: 'top-right',
timeout: 5000
});
}
});
Also please note, you should not be using an ID within a for loop like id="CheckedResumeId". This will create multiple ID's of the same type and cause issues for you. I'd advise changing this to a class
ID attribute for an HTML element should be unique. In the code snippet which you've shared, duplicate hidden form elements with ID 'CheckedResumeId' will be created which will pollute the HTML DOM. You can take the element outside of foreach and check the code. Like Below
<input type="hidden" name="CheckedResumeId" id="CheckedResumeId" />
#foreach (var item in NurseOneStop.WebSite.Models.ApplicationSession.CurrentUser.NurseResumeList)
{
<div class="col-md-12 lstCard">
<input type="radio" name="RBCheckedResume" style="height: 15px; width: 18px;" onchange="CheckedResume(#item.ResumeId)" />
<span>#item.ResumeName</span>
</div>
}
Here goes the JS to check if radio button is clicked when executing the onsubmit function.
if($('#CheckedResumeId').val().trim() == "") {
//Give an error message to user saying that the radio button is not clicked.
}
I was trying to set the array values to the input field named attachments[]
I have array stored in js variable attachArray
What I have tried is,
$('[name="attachments"]').attr('value', attachArray);
or
$('[name="attachments"]').val(attachArray);
But getting empty attachments in the controller like this,
array(1) { ["attachments"]=> array(1) { [0]=> string(0) "" } }
What I'm doing wrong?
EDIT
<div class="col-md-4">
<div class="form-group ticket-align">
<label>Attachment</label>
<label class="btn btn-primary" data-toggle="modal" data-target="#t-attachment-modal">
Browse…
<input type="hidden" name="attachments[]">
</label>
<span id="fileList"></span>
<span class="error" id="error-atachments" style='display: none;'></span>
</div>
</div>
As far as I understand is that you want to spread the content of an JavaScript array to multiple fields that PHP on the other hand interprets as an array.
I changed the inputs from hidden to text just to make it a little bit more clear and so you can see how the values do look like. Don't forget to undo this in your code.
const attachArray = [
'val1',
'val2',
];
const attachments = $('[name="attachments[]"]');
for ( let i = 0; i < attachments.length; i += 1 ) {
$( attachments[ i ] ).val( attachArray[ i ] );
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-4">
<div class="form-group ticket-align">
<label>Attachment</label>
<label class="btn btn-primary" data-toggle="modal" data-target="#t-attachment-modal">
Browse… <br>
<input type="text" name="attachments[]"><br>
<input type="text" name="attachments[]">
</label>
<span id="fileList"></span>
<span class="error" id="error-atachments" style='display: none;'></span>
</div>
</div>
But this is a lot of code to do. I think it might be easier to send the array as JSON and use PHPs json_decode to convert it back into an array, like so:
const attachArray = [
'val1',
'val2',
];
$('[name="attachments"]').val( JSON.stringify( attachArray ) );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-4">
<div class="form-group ticket-align">
<label>Attachment</label>
<label class="btn btn-primary" data-toggle="modal" data-target="#t-attachment-modal">
Browse… <br>
<input type="text" name="attachments">
</label>
<span id="fileList"></span>
<span class="error" id="error-atachments" style='display: none;'></span>
</div>
</div>
And do something like
$attachments = json_decode( $_POST[ 'attachments' ] );
Since it's a hidden input, so
Either:-
$('[name=attachments]').val(attachArray);
OR
$('input:hidden[name=attachments]').val(attachArray);
Will work.
Note:- Use the backslashes(Escape internal brackets with \\(no space)).
you have input field with name as attachments[] so try this
$('[name="attachments[]"]').val(attachArray);
Mention id to a hidden field and you are sending array through the form so declare hidden field name with square brackets like below.
<input type="text" name="attachments[]" id="attachments">
And bind your array with the jquery val() method.
$('#attachments').val(attachArray);
For Future Reference :-)
I have a form within a bootstrap modal. I would like the input fields to display the past values that the user entered the first time they filled out the form, which I am retrieving from a cloudant database. I would like these input fields to be editable so that the user can resubmit the form with any changes they may have. However, I am stuck when trying to display the past information in the input fields. I can't find any reason why these value of the input fields are not being changed.
The javascript that adds my buttons to my boostrap list-group:
var loadIotPanel = function(iotsJSON)
{
for(var iot in iotsJSON)
{
var button = $('<button/>').text(iotsJSON[iot].appID).addClass('list-group-item iot').attr({name:iotsJSON[iot].appID, "aria-label": "Quick View IoT", "data-toggle": "modal", "data-target": "#quick-view-iot-modal", type: "button"});
$('#iot-list').append(button);
}
};
The html where my button will be placed within my list-group:
<div class="row">
<div class="col-lg-4 col-md-6 col-sm-12 col-sm-12 dash-col">
<button name="edit-iots" aria-label="Edit IoTs" data-toggle="modal" data-target="#edit-iots-modal" type="button" class="icon"><span class="glyphicon glyphicon-edit gray"></span></button>
<p class="fancy-font dash-item-title">Your IoTs</p>
<button name="add-iot" aria-label="Add IoT" data-toggle="modal" data-target="#connect-iot-modal" type="button" class="icon"><span class="glyphicon glyphicon-plus gray"></span></button>
<div class="list-group iot" id="iot-list"><!-- buttons will be placed here --></div>
</div>...
The modal that pops up when clicking a button:
<div class="modal fade" id="quick-view-iot-modal">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="quick-view-iot-h4"></h4>
</div>
<div class="modal-body">
<form id="edit-iot-form" method="post">
IoT Name: <br>
<input type="text" name="iot-name" class="iot-value" required><br>
Organization ID: <br>
<input type="text" name="org-id" class="iot-value" readonly required><br>
Authentication Method: <br>
<input type="text" name="auth-method" class="iot-value" value="apikey" readonly><br>
API Key: <br>
<input type="text" name="api-key" class="iot-value" readonly required><br>
Authentication Token: <br>
<input type="text" name="auth-token" class="iot-value" readonly required><br>
</form>
<button name="more" type="button" class="fancy-font page-button">More</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
The javascript that adds the content to modal. It is within a main method that is called when document is ready:
$('.iot').click(
function()
{
var iotName = event.target.name;
getIots(loadIotQuickView, iotName);
$('h4#quick-view-iot-h4.modal-title').text(event.target.name);
});
The getIots() function: (it includes parameter variable=null because I also use it in another part of code where the varaible parameter is not used. This method sends an ajax post to a servlet, which then responds with an array of iot objects)
var getIots = function(callback, variable=null)
{
var iotsJSON = null;
$.post("DashboardServlet", {loadIotPanel: "true"}, function(response)
{
iotsJSON = response;
callback(response, variable);
});
The loadIotQuickView() function: (This is where I believe I am getting problems)
var loadIotQuickView = function(iotsJSON, iotName)
{
var currentIoT = null;
for(var iot in iotsJSON)
{
if(iotsJSON[iot].appID = iotName)
currentIoT = iotsJSON[iot];
}
if(currentIoT == null)
return;
$('.iot-value[name="iot-name"]').attr("value",currentIoT.appId);
};
I've tried numerous jquery selectors but none of the input field values within the form will change. I've stepped through the code and all of my variables have the correct values that its just the last line that's not executing how I want. I am unsure if there is an issue with my jquery selector or if it is something else. Thanks in advance!
UPDATE:
I've tried the following selectors:
$('.iot-value[name="iot-name"]')
$('input[name="iot-name"]')
$('.iot-value')
$('#connect-iot-modal').find('input[name="iot-name"]')
I've also tried adding an id of "edit-iot-name" to my input field:
$('#edit-iot-name')
$('#connect-iot-modal #edit-iot-name')
But none of these have worked, which leads me to believe that it must not be an issue with my selector.
UPDATE:
I've also tried using .val(currentIoT.appID) with all of the previous selectors. Still not working.
I'm not sure why, but adding the id of the modal that my form is in, which is #quick-view-iot-modal, to my selector worked. However for some reason it only works when I use .val() and not when I use .attr(). So the final result is:
$('#quick-view-iot-modal #edit-iot-name').val(currentIoT.appID);
I'm not sure why it is required to add the id of the modal, and I'm not sure why it doesn't work like this:
$('#quick-view-iot-modal #edit-iot-name').attr("value",currentIoT.appID);
But it works! If anyone knows why it only works with this combination, please let me know!
try:
$('.iot-value[name="iot-name"]').val(currentIoT.appId);
Your selector is pretty weird as well. why not just refer to the input by name?
$('input[name="iot-name"]').val(currentIoT.appId);
In your code here:
$('.iot-value[name="iot-name"]')
"iot-name" is a string literal, and it will not evaluate to the value of your iot-name variable.
I'm guessing that you are looking to use the variable's value in your selector, which would look like this:
$('.iot-value[name="' + iot-name + '"]')
I have been struggling with this problem for 3 hours. The realisation that you must reference the object through the modal div is the winner.
I was trying to do 2 things:
populate the href in an <a> button on my modal
set the value of another field using an onChange()
so I end up with:
$("#modal-form #linkbtn").attr("href", url);
$('#modal-form #inputfield").val(newVal);
Thanks so much for this hint.
LISTEN!
i've got a good solution for all of you guys!
$("#exampleModal").modal("show");
$(function () {
$("#exampleModal #ticket_id").val("your_value_variable");
});
try this way after you load your modal show it then use DOM ready event then set your value to it input text and amazingly it works! this is the easiest and simplest way from me