The Background
I have the following HTML document:
<!-- file: index.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Form</title>
<!-- Plugins CSS -->
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/bootstrap-combobox.css">
</head>
<body class="one-page fixed-header">
<div class="page-box">
<div class="page-box-content">
<h3>Form 1</h3>
<div class="content">
<div class="combobox-container" id="employee-name-box">
<label for="addScheduleLoc">Location: <span class="required">*</span></label>
<select class="form-control combobox location" name="addScheduleLoc" id="addScheduleLoc" required>
<option value selected="selected">---Select Location---</option>
</select>
</div>
<div class="combobox-container" id="employee-name-box">
<label for="addScheduleTier">Tier: <span class="required">*</span></label>
<select class="form-control combobox tier" name="addScheduleTier" id="addScheduleTier" required>
<option value selected="selected">---Select Tier---</option>
</select>
</div>
</div>
<hr>
<h3>Form 2</h3>
<div id="changeScheduleModalBody" class="content">
<div class="combobox-container" id="employee-name-box">
<label for="chScheduleLoc">Location: <span class="required">*</span></label>
<select class="form-control combobox location" name="chScheduleLoc" id="chScheduleLoc" required>
<option value selected="selected">---Select Location---</option>
</select>
</div>
<div class="combobox-container" id="employee-name-box">
<label for="chScheduleTier">Tier: <span class="required">*</span></label>
<select class="form-control combobox tier" name="chScheduleTier" id="chScheduleTier" required>
<option value selected="selected">---Select Tier---</option>
</select>
</div>
</div>
</div>
<!-- .page-box-content -->
</div>
<!-- .page-box -->
<script src="js/jquery-2.1.3.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/bootstrap-combobox.js"></script>
<script src="js/testJavascript.js"></script>
</body>
</html>
There is an AJAX call to a server which retrieves some data after the page has loaded and puts the data into a variable and is used to populate the comboboxes. There are multiple comboboxes that should contain the same information (eg. All comboboxes with class "location" should contain the same list of locations). I have simulated this in the following javascript file. Please note that the initialization of the comboboxes must happen first because I may need to update the contents of the associated <select> element after the combobox is initialized.
//file: js/testJavascript.js
var options = {
locations: "<option id='1'>London</option><option id='2'>Los Angeles</option><option id='3'>Sydney</option>",
tiers: "<option id='1'>Upper</option><option id='2'>Middle</option><option id='3'>Lower</option>"
}
$(document).ready(function(){
$('.combobox').combobox({
bsVersion: '3'
}); //This statement cannot be moved.
$('select.location').append(options.locations);
$('select.tier').append(options.tiers);
});
The Problem
The problem that I'm running into is after I append the options to the <select> elements, the comboboxes aren't updated to show the most recent information. I realize that if I call $('.combobox').combobox({...}); after options are added, the combobox will be correct. But I may need to update the information in the comboboxes after the comboboxes are initialized the first time.
The Question
How can I get the comboboxes to update after I add options to the corresponding <select> tag and after they have already been initialized?
After some more research and fiddling around, I found that the following code works to refresh the combobox. (using the issue shown here)
$('select.location').each(function(){ //need to run in .each to refresh all the elements
$(this).data('combobox').refresh();
});
$('select.tier').each(function(){
$(this).data('combobox').refresh();
});
Try to refresh your combobox using the following code :
$('select.location', 'select.tier').data('combobox','refresh');
Hope this helps.
Related
This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 1 year ago.
I have a hidden div called recipeDetailsDiv inside a form as below
$("#recipes").change(function() {
var selectedVal = $("#recipes").val();
if (selectedVal != "") {
$("#recipeDetailsDiv").show();
}
});
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<form>
<div class="form-group">
<div class="row">
<div class="col-sm">
<label for="recipes">Recipes</label>
<select class="form-control" id="recipes" name="recipes" required>
<option></option>
<option>1</option>
<option>2</option>
</select>
</div>
</div>
</div>
<div class="card" style="margin-top: 10px;" id="recipeDetailsDiv" hidden>
<ul class="list-group list-group-flush">
<div id="populateRecipeDetails">Recipe Details</div>
</ul>
</div>
</form>
I am trying to show the hidden div when someone changed the drop down box
I included jQuery CDN too. But it is not showing on change of drop down box. This could be a simple problem. But I cannot figure out how to solve. Can someone help?
Edit 1
I have the following codes included in the following order
<?php include "commonFiles/assignModal.php"; ?>
<?php include "../commonFilesForAll/jsLibraries.php"; ?>
jsLibraries.php contain CDN.
assignModal.php is the same HTML codes I showed above
Your code is working fine. So as #Phil's comment, you should show us the side effect rendering code. Because it may be this problem: Event handler not working on dynamic content
Besides, I would suggest enhancement your logic code.
There are 2 ways to resolve:
Using toggle to handle the case empty select.
If the selected item is diff empty then use show, else then use hide
$("#recipes").change(function() {
const isToggle = $("#recipes").val() !== "";
$("#recipeDetailsDiv").toggle(isToggle);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="form-group">
<div class="row">
<div class="col-sm">
<label for="recipes">Recipes</label>
<select class="form-control" id="recipes" name="recipes" required>
<option></option>
<option >1</option>
<option>2</option>
</select>
</div>
</div>
</div>
<div class="card" style="margin-top: 10px;" id="recipeDetailsDiv" hidden>
<ul class="list-group list-group-flush">
<div id="populateRecipeDetails">Recipe Details</div>
</ul>
</div>
</form>
If recipes are optional and empty option are selected, you only need show div when an option are selected.
$("#recipes").change(function() {
$("#recipeDetailsDiv").show();
});
The show problem, you can refactor it for class. Creating a class which hides your div and use jQuery.removeClass().
I am beginner in java and not familiar with javascript or php, so I just can explore and copypast simplies exemplars of javascript/php code for my needs. So that what I did find in stackowerflow and try to implement for my need:
Script:
<script type="text/javascript">
function onchange() {
var e = document.getElementById("persId");
var persSelected = e.options[e.selectedIndex].text;
document.getElementById("myInput").value=persSelected;
}
</script>
And body:
<body>
<div th:replace="fragments/main.html :: top_menu"/>
<div class="w3-container" align="center">
<form action="/add" method="post" class="w3-container w3-card-4 w3-light-grey w3-text-blue w3-margin w3-center" style="width: 50%" >
<h2 class="w3-center">Add the challenger</h2>
<select name="pers" id="persId" onchange="onchange();">
<option th:each="person: ${personList}">
<title id="titleId" th:text="${person.getName()}"/>
</option>
</select>
<div class="w3-row w3-section">
<div class="w3-col" style="width:50px"><i class="w3-xxlarge fa fa-user"></i></div>
<div class="w3-rest">
<input class="w3-input w3-border" id="myInput" name="lastName" type="text" onkeyup="myFunction()" placeholder="Search for last names.." title="Type in a last name">
</div>
</div>
I get the list of person into drop list, but not have the selected item into input text field.
How to correctly implement this code?
There are to problems with your code
options don't have title elements
since there are no title elements you have to get the selected value from the select element
Let me explain.
This code makes no sense:
<option th:each="person: ${personList}">
<title id="titleId" th:text="${person.getName()}"/>
</option>
Options don't have titles. Instead you should just use text inside of options.
Like this:
<option th:each="person: ${personList}">
${person.getName()} // this should just turn into text
</option>
so you will end up with:
<option th:each="person: ${personList}">
John Doe
</option>
okay first thing done now to fix your other problem. :)
This line could have worked.
var persSelected = e.options[e.selectedIndex].text;
but since there are no element inside the option, then we need to get the value somewhere else.
The easiest way to do so would be to get the value of the select element.
like this:
var persSelected = document.getElementById("persId").value;
here is an example of a working script file:
Script:
<script type="text/javascript">
function onchange() {
var persSelected = document.getElementById("persId").value;
document.getElementById("myInput").value = persSelected;
}
</script>
Seems like this line:
document.getElementById("persId").value=persSelected;
Should be:
document.getElementById("myInput").value=persSelected;
I dont know - how and why are using parameter type in script block.. But, when I erase this code: type="text/javascript" all works well
I 've written the following code snippet in Eclipse html form which include headings and titles in greek characters.
My problem is that these characters can't be correctly displayed in my web browser's page although I've set UTF-8 Encoding. Instead, they are displayed like question symbols (????).
My code snippet:
var product = $scope.product = []; // Custom JavaScript creates a JavaScript Object and binds it to the current AngularJS $scope of the form as a variable named "product".
$scope.addProduct = function () { // We make a function named "addProduct".
var product = {}; // We add a new "product" to the Array.
product.Category = $scope.Category;
product.Description = $scope.Description;
if (!!$scope.camForm.fields[0].element[0].files[0]) {
product.Details = $scope.camForm.fields[0].element[0].files[0].name; // We check whether a file is uploaded.
} else {
return; // If no file is uploaded, it returns "undefined".
}
product.Price = $scope.Price;
$scope.product.push(product); // We use the value of the "product" input field to add a new "product" to the Array.
$scope.Category = ""; // We clear the TextBox "���������".
$scope.Description = ""; // We clear the TextBox "���������".
$scope.Details = ""; // We clear the TextBox "������������".
$scope.Price = ""; // We clear the TextBox "����".
};
$scope.removeProduct = function (index) { // We make a function named "removeProduct".
var category = $scope.product[index].Category; // We find product's Category using "index" from the Array and binds it to the current AngularJS $scope of the form as a variable named "category".
$scope.product.splice(index, 1); // We use an index to remove a "product" from the Array.
}
$scope.isAddFormValid = function () { // We make a function named "isAddFormValid".
return ($scope.Category &&
$scope.Description &&
$scope.camForm.fields[0].element[0].files[0] &&
$scope.Price) ? true : false; // If all of the 4 parameters of variable "product" are added, the value will be "true", otherwise the value will be "false".
}
camForm.on('form-loaded', function() { // We hook into the lifecycle of Camunda SDK JS Form.
camForm.variableManager.createVariable ({ // We "create" (declare) a new process variable
name:'product', // named 'product' and
type:'json', // provide as type information 'json' used for serialization.
value:product
});
});
camForm.on('submit', function(evt) { // We hook into the lifecycle of Camunda SDK JS Form.
if (product.length<1) { // If no "product" is added,
evt.submitPrevented = true; // an event handler prevents the form from being submitted by setting the property "submitPrevented" to 'true'.
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form role="form" name="insertForm" accept-charset="utf-8">
<h2><b>����� ���������</b></h2> <!-- We set the heading of the HTML Table. -->
<div>
<table style="width:100%;">
<thead> <!-- We group the header content in the HTML Table. -->
<tr> <!-- The header content of the HTML Table is not repeated. -->
<th style="width:140px;">���������</th>
<th style="width:305px;">���������</th>
<th style="width:250px;">������������</th>
<th style="width:75px;" >���� (�)</th>
<th></th>
</tr>
</thead>
<tbody ng-repeat="x in product track by $index"> <!-- The HTML Table is populated from the JSON Array "product", using a "ng-repeat" directive which is assigned to each row of the Table in order to repeat all the objects of the Array. -->
<tr> <!-- Each row of the HTML Table consists of 4 HTML Input Form fields and 1 button. -->
<td><input style="width:140px;" type="text" value="{{x.Category}}" /></td>
<td><input style="width:305px;" type="text" value="{{x.Description}}" /></td>
<td><input style="width:250px;" type="text" value="{{x.Details}}" /></td>
<td><input style="width:75px;" type="number" value="{{x.Price}}" /></td>
<td><input type="button" ng-click="removeProduct($index)" value="Remove" /></td> <!-- The "ng-click" directive is assigned to the "Remove" button and calls the function named "removeProduct" with the current "$index" when this button is clicked. -->
</tr>
</tbody>
</table>
</div>
<hr> <!-- We separate the HTML content. -->
<div>
<h2><b>���������� ��� ������</b></h2> <!-- We set the heading of the HTML Form. -->
<div class="row"> <!-- We set the "1st row" of the HTML Form. -->
<div class="col-md-6"> <!-- We use "md" for "medium" screen devices of width equal to or greater than 992px and "6" for adding 6 columns. -->
<div class="form-group"> <!-- We use "form-group" for optimum spacing. -->
<label class="control-label" for="category">���������</label>
<div class="controls">
<input style="width:140px;" id="category" type="text" ng-model="Category" /> <!-- The "ng-model" directive binds the value of the "���������" input field to the created variable "Category" in AngularJS. -->
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-label" for="Description">���������</label>
<div class="controls">
<input style="width:305px;" id="Description" type="text" ng-model="Description" /> <!-- The "ng-model" directive binds the value of the "���������" input field to the created variable "Description" in AngularJS. -->
</div>
</div>
</div>
</div>
<div class="row"> <!-- We set the "2nd row" of the HTML Form. -->
<div class="col-md-6">
<div class="form-group">
<label class="control-label" for="Details">������������</label>
<div class="controls">
<input style="width:250px;"
id="Details"
type="file"
cam-variable-name="Details"
cam-variable-type="File"
cam-max-filesize="10000000" ng-model="Details" /> <!-- The "ng-model" directive binds the value of the "������������" input field to the created variable "Details" in AngularJS. -->
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-label" for="price">���� (�)</label>
<div class="controls">
<input style="width:75px;" id="price" type="number" ng-model="Price" /> <!-- The "ng-model" directive binds the value of the "���� (�)" input field to the created variable "Price" in AngularJS. -->
</div>
</div>
</div>
</div>
<div class="row"> <!-- We set the "3rd row" of the HTML Form. -->
<div class="col-md-4"> <!-- We use "md" for medium screen devices of width equal to or greater than 992px and "4" for adding 4 columns. -->
<div class="controls">
<input type="button" ng-click="addProduct()" ng-show="isAddFormValid()" value="Add" /> <!-- The "ng-show" directive shows the input element ("Add" button) only if the "isAddFormValid()" expression (function) returns "true". The "ng-click" directive is assigned to the "Add" button and calls the function named "addProduct()" when this button is clicked. -->
</div>
</div>
</div>
</div>
<script src="insert-products-and-specifications.js" charset="utf-8" cam-script type="text/form-script"></script> <!-- We call the external script file ("insert-products-and-specifications.js"). -->
</form>
</body>
</html>
Does anyone have any idea on this please?
Thanks,
Steve
The following works :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form role="form" name="startForm" accept-charset="utf-8">
<h2>Ώρα για προμήθειες</h2>
</form>
</body>
</html>
Try this one:
<!doctype html>
<html lang="el">
<head>
<meta charset="utf-8">
<title>Hello, world!</title>
</head>
<body>
<form role="form" name="startForm" accept-charset="utf-8">
<h2>Ώρα για προμήθειες</h2>
</form>
</body>
</html>
I managed to solve my issue.
I didn't modify something in my code.
The solution was to change some general settings in my eclipse editor.
For anyone who may face the same encoding issue in eclipse, I wrote the following steps:
check and maybe change the following preferences in your eclipse.
The encoding of the text editor should be UTF-8.
– General -> Editors -> Text Editors -> Spelling -> Encoding -> Default UTF-8
The encoding for the HTML files should be UTF-8. For that, you can configure to use the workspace encoding.
– Web -> HTML-Files -> Use workspace encoding
The encoding of your workspace should be UTF-8.
– General -> Workspace -> Text file encoding -> Other -> UTF-8
You should also check the encoding of your resource. For that, please click with the right mouse button on your eclipse project and choose Properties. In the new opened window, click on Resource and check the value of the Text file encoding
I'm trying to use the Google Chrome Storage API (https://developer.chrome.com/extensions/storage) to persist a textarea that acts as a persistent notes field in my plugin
In the HTML I have a handler setup to run save_notes on blur.
I want to fire load_notes() immediately if the textarea is blank. save_notes should save the textarea to object key 'stored_obj'
I didn't code it right and it's not working, anyone see the issue?
notes.js
///// select the text area
// var note_area = document.getElementById("textarea")
var note_area = document.querySelector("#textarea")
//// create a function to save the textarea to local storage
// I'll also want to check & load previously saved notes
;(function load_notes () {
if (!note_area) {
note_area.value = chrome.storage.sync.get(stored_obj)
}
})()
function save_notes () {
chrome.storage.sync.set({
stored_obj: note_area
}, function () {
console.log("Saved into Chrome Storage")
})
}
//// setup a blur handler in notes.html to fire function save_notes
notes.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Note Screen</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css">
<link rel="stylesheet" href="style.css">
<script src="scripts/notes.js"></script>
</head>
<body>
<div class="container">
<ul class="nav nav-tabs">
<li>Settings</li>
<li role="presentation" class="active">Notes</li>
</ul>
<div id="notes-header">
<h1 id="noteh1">Note Screen</h1>
</div>
<hr>
<div class="row">
<div class="col-sm-8" id="notes-section">
<h2>Websurf Notes</h2>
<p>Write notes here. Reference them to do searches and checks during free time</p>
<!--<button id='notesave' class="btn btn-primary">Save Notes & Close Tab</button>-->
<br>
<textarea name="ntxt" id="notetext" cols="20" rows="20" class="form-control" onblur="save_notes()"></textarea>
</div>
<div class="col-sm-4">
<h2>Override</h2>
<p>Things that demand an immediate view are the ONLY intended targets of this override</p>
<div class="form-group">
<!--<form action="" class="form-control">-->
<select name="" id="bypass-limit" class="form-control">
<option value="">Bypass Time Limit</option>
<option value="5">5 minutes</option>
<option value="10">10 minutes</option>
<option value="15">15 minutes</option>
<option value="20">20 minutes</option>
<option value="30">30 minutes</option>
</select>
</div>
<div class="form-group">
<button id="bypass-button" class="btn btn-danger">
Bypass Now (action will be logged)
</button>
<!--</form>-->
</div>
</div>
</div>
</div>
</body>
</html>
chrome.storage.sync.get() is an asynchronous function just like set() is. You have the proper callback function set up for set(), but not get:
chrome.storage.sync.get("stored_obj", function(result) { note_area.value = result } );
That is the first thing that jumps out at me, there may be other errors.
Wrong id
In var note_area = document.querySelector("#textarea")
note_area will always return null. There is id such as textarea it is notetext or use
var note_area = document.querySelector("textarea")
Also in the if statement if(note_area.val === "")
Inline event handler
Extension produces following error on run
Refused to execute inline event handler because it violates CSP.
this because of onblur="save_notes()"
It is not allowed now. Instead, use this in your js file document.querySelector("#notetext").addEventListener("blur", save_notes);
chrome.storage.sync
chrome.storage.sync.get(stored_obj)
stored_obj does not exit! so it can't get you anything from the store use this instead.
chrome.storage.sync.get("stored_obj")
It will return you an object resultObject do resultObject.stored_obj to get the value.
You need to pass note_area.val in set
I am successfully validating a required field using jQuery Validate method. Everything works fine but I want to display the error message inside ia div tag which an option to make the error disappear after 10 or 20 sec of showing it, basically like a auto hide.
here is the markup I have created
<script type="text/javascript">
$(document).ready(function(){
$("#cForm").validate({
rules: {
PaymentMethod: {
required: true
}
,ShippingMethod: {
required: true
}
},
messages: {
PaymentMethod: {
required:" Select a payment method!"
}
,ShippingMethod: " Select a shipping method!."
}
});
});
</script>
<sytle="text/css">
#ship-msg, #pay-msg {display:none; background:url("/image/req.gi") no-repeat left center transparent;}
.msg { color:#000;}
</style>
<form id="cForm" method="post" action="/pay.html">
<div class="ship-options">
<label for="ShippingMethod">Shipping Method</label>
<select id="ShippingMethod" name="ShippingMethod" >
<option value="">Choose Shipping Method</option>
<option value"UPS-GROUND">UPS GROUND</option>
<option value"UPS-1DAY">UPS 1DAY</option>
<option value"UPS-2DAY">UPS 2DAY</option>
</select>
<div id="ship-msg><div class="msg"> // display the error messgae here </div>
</div>
<div class="pay-options">
<label for="PaymentMethod">Payment Method</label>
<select id="PaymentMethod" name="PaymentMethod" >
<option value="">Choose Paymenet Method</option>
<option value"VISA">VISA</option>
<option value"MASTERCARD">MASTERCARD</option>
<option value"AMEX">AMERICAN EXPRESS</option>
</select>
<div id="pay-msg><div class="msg"> // display the error messgae here </div>
</div>
<input type="submit" value="Continue" id=" />
</form>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.8/jquery.validate.min.js"></script>
and so when some clicks the continue button and if the methods are not selected display them display the respective divs and its message
I know i am missing something
Thanks and appreciate it
You misspelled the opening <style> tag. Therefore #ship-msg, #pay-msg won't be hidden:
<sytle="text/css"> ... </style>
Your script must be placed after jQuery has been loaded. That is at the end of your document. If you place it before the jQuery script is loaded, the browser won't recognize function calls like $(document).ready() and $("#cForm").validate().
I am assuming that the obvious mistakes (jQuery reference BEFORE the code and style tag mispelling) were simple oversights on your part and that you want to know how to make the appearing/disappearing happen. If you want to make the error appear and then go away after some time, when the validation fails call this function:
function ToggleErrorMessage(messageDiv) {
messageDiv.toggle().delay(20000).toggle();
}
Which will turn the div on, wait 20 secs, and then turn it off. "messageDiv" is the div which you want to apply this to.
This isn't strictly using your validate but this should help you on your way
example