JavaScript and hidden input - javascript

I am having a problem setting/getting a hidden input's value with JavaScript, and can't see what I'm doing wrong.
What I am basically trying to do is maintain the state of expandable/collapsable divs on my page across form submissions. So I put a hidden input on the page to hold the state of the divs. When a div is expanded/collapsed, I change the value of the input. When the page loads, I read the value of the input and set the state of the divs.
But the value of the input is getting lost. I verify through alerts that it is being set correctly, and then when I read it on load, I verify with an alert that it is empty. Here is the pertinent code:
<input type="hidden" name="ECState" id="hdnECState" />
<script language="javascript" type="text/javascript">
<!--
var ecValue;
function ec(div, btn) {
//expands or collapses an error detail div
var e = document.getElementById(div);
var b = document.getElementById(btn);
var ecStr = div.toString() + ',' + btn.toString() + '|'
if (e.style.display == 'block') {
e.style.display = 'none';
b.src = '../../Images/plus.gif';
ecValue = ecValue.replace(ecStr, '');
}
else {
e.style.display = 'block';
b.src = '../../Images/minus.gif';
ecValue = ecValue + ecStr;
}
alert(ecValue);
document.getElementById('hdnECState').value = ecValue;
}
function reexpand() {
//restores the expanded state of the error detail divs
var pipe, comma, db, div, btn, e, b;
var n = document.getElementById('hdnECState').value;
alert('n=' + n);
if (n != '') {
pipe = n.indexOf('|');
while (pipe > 0) {
db = n.substring(0, pipe);
comma = db.indexOf(',');
if (comma > 0) {
div = db.substring(0, comma);
btn = db.substring(comma + 1);
e = document.getElementById(div);
b = document.getElementById(btn);
e.style.display = 'block';
b.src = '../../Images/minus.gif';
}
n = n.substring(pipe+1);
pipe = n.indexOf('|');
}
}
}
reexpand();
//-->
</script>
When I expand a div, I see the alert from ec() showing that ecValue is 'foo,bar|'.
But after submitting the form, I see the alert from reexpand() saying 'n='.
Anybody see what I'm missing?

You haven't posted Html part of your code. So I am a bit confused, But I think you should put some value first.
<input type="hidden" name="ECState" id="hdnECState" value="1" />

Rudu supplied the answer in a comment, but since I can't mark a comment as the answer, here it is:
I was forgetting that hidden inputs don't automatically keep their value in ViewState across form submissions. I needed to re-value the hidden input on the back end in page load and then everything worked fine.

Related

How do I get the id of a element in a form?

I need to get the id of an element within a form so I can tag the element as "false" or "true". Or, alternately, I need a way to associate a name with an element that can I pull in javascipt so I can change the associated value.
var form = document.getElementById("myForm");
form.elements[i].value
Those lines of code is what I tried but it doesn't seem to work.
Edit:
function initial(){
if (localStorage.getItem("run") === null) {
var form = document.getElementById("myForm").elements;
for(var i = 0; i < 1 ; i++){
var id = form.elements[i].id;
sessionStorage.setItem(id,"false");
}
localStorage.setItem("run", true);
}
}
So basically when I run the page, I want a localStorage item attached to all the buttons on the screen. I want this to run once so I can set all the items to false. Problem is I don't know how to get the ids so I have a value to attach to the button. Any idea of how to accomplish a task like this.
Edit2:
function initial(){
if (localStorage.getItem("run") === null) {
var form = document.getElementById("myForm");
var tot = document.getElementById("myForm").length;
for(var i = 0; i < tot ; i++){
sessionStorage.setItem(form.elements[i].id,"false");
}
localStorage.setItem("run", true);
}
}
This is the new code. It mostly seems to work but for some reason only the first value is getting set to false. Or maybe it has to do with this function, I'm not sure.
function loader(){
var form = document.getElementById("myForm");
var tot = 5;
for(var i = 0; i < 5 ; i++){
if(sessionStorage.getItem(form.elements[i].id) === "true"){
document.getElementById(form.elements[i].id).style.backgroundColor = "green";
return ;
}else{
document.getElementById(form.elements[i].id).style.backgroundColor = "red";
return false;
}
}
}
Anyways, I'm running both of these at the same time when the page is executed so they are all set to false and turn red. But when a button is properly completed, the color of the button turns green.
It's available via the id property on the element:
var id = form.elements[i].id;
More on MDN and in the spec.
Live Example:
var form = document.getElementById("myForm");
console.log("The id is: " + form.elements[0].id);
<form id="myForm">
<input type="text" id="theText">
</form>
You're already storing all the elements in the form so it must be :
var form = document.getElementById("myForm").elements;
var id = form[i].id;
Or remove the elements part from the form variable like :
var form = document.getElementById("myForm");
var id = form.elements[i].id;

"reuse" a JavaScript code for multiple buttons

I am fairly new to JavaScript,
I have ben working on a simple if else script to change the color of at button, depending on the status of a variable that I get from a plc (Siemens S7-1200).
The script is working fine and the color of the button is changing.
But I have 10 buttons that I want to run this script on.
Is it possible to “reuse” the script so that I don’t have to copy the script and change the variables for every button
T
<script>
var tag = ':="web_DB".outtag1:'
var button = "button1"
window.onload = function() {
if (tag == 1) {
document.getElementById(button).style.backgroundColor = 'green';
} else{
document.getElementById(button).style.backgroundColor = 'red';
}
}
</script>
<form>
<input type="submit" id="button1" value="button">
<input type="hidden" name='"web_DB".intag1' value ="1">
</form>
It's hard to be sure since you haven't posted all your code and what you have posted doesn't actually work but I think you're looking for something like this.
const tags = [
':="web_DB".outtag1:',
':="web_DB".outtag2:',
//...
':="web_DB".outtag10:'
];
window.onload = function() {
for (let i = 0; i <= 9; i++) {
const color = (tags[i] == 1) ? 'green' : 'red';
document.getElementById('button' + (i+1)).style.backgroundColor = color;
}
}

Find next text by search and highlight not works

When search any text on search box, it can be find and highlighted the correct text, but when search next/new text, it's unable to find the next/new text, it's not working when search again, i'm unable to find the issue. The JS below.
JS
$('button#search').click(function() {
var page = $('#ray-all_text');
var pageText = page.html().replace("<span>", "").replace("</span>");
var searchedText = $('#searchfor').val();
var theRegEx = new RegExp("(" + searchedText + ")", "igm");
var newHtml = pageText.replace(theRegEx, "<span>$1</span>");
page.html(newHtml);
$('html, body').animate({
scrollTop: $("#ray-all_text span").offset().top }, 2000);
});
HTML
<div class="ray-search">
<div class="field" id="ray-search-form">
<input type="text" id="searchfor" placeholder="what are you searching for?" />
<button type="button" id="search">Press to Find!</button>
</div>
</div>
<article id="ray-all_text">
<p>
This manual and web site, all information and data and photos contained herein, are the s...
</p>
</article>
Please check the live Example: https://jsfiddle.net/gaezs6s8
Why is this happening? Is there a solution?
My suggestion is to make a few validations before change all the .html() inside the text you want to avoid unexpected behaviors and improve the functionality.
First make a validation to avoid the 'space' as the first value on the input, this will let us later check if the input has a real value inside.
$('body').on('keydown', '#searchfor', function(e) {
if (e.which === 32 && e.target.selectionStart === 0) {
return false;
}
});
Code from this answer
Now Please check the comments on your code:
//Create some vars to later check for:
//['text you are searching', 'number of highlights','actual highlight']
var searching,
limitsearch,
countsearch;
$('button#search').click(function() {
var searchedText = $('#searchfor').val();
var page = $('#ray-all_text');
//Now check if the text on input is valid
if (searchedText != "") {
//If the actual text on the input is different from the prev search
if(searching != searchedText) {
page.find('span').contents().unwrap();
var pageText = page.html();
var theRegEx = new RegExp("(" + searchedText + ")", "igm");
var newHtml = pageText.replace(theRegEx, "<span>$1</span>");
page.html(newHtml);
//Set your variables to the actual search
searching = searchedText;
limitsearch = page.find('span').length;
countsearch=0;
} else {
//If it's the same of the prev search then move to next item instead of repaint html
countsearch<limitsearch-1 ? countsearch++ : countsearch=0;
console.log(countsearch+'---'+limitsearch)
}
//Go to target search
$('body').animate({
scrollTop: $("#ray-all_text span").eq(countsearch).offset().top - 50},
200);
} else {
alert('empty search')
}
});
JqueryDemo

forEach loop for String array

I have a string array(APN) in my bean(accessed as header). I am accessing it like this
<c:forEach var="apn" items="${header.APN}" >
var g = apn;
if (g.length!=0 && g!="null"){
if(counter == 1){
count=0;
$("#img0").show();
$("#apn0").show();
$("#rtu0").show();
}
if(counter == 2){
count=1;
$("#img0").hide();
$("#apn0").show();
$("#rtu0").show();
$("#img1").show();
$("#apn1").show();
$("#rtu1").show();
$("#removeimg1").show();
}
if(counter == 3){
count=2;
$("#img0").hide();
$("#apn0").show();
$("#rtu0").show();
$("#img1").hide();
$("#apn1").show();
$("#rtu1").show();
$("#removeimg1").hide();
$("#img2").show();
$("#apn2").show();
$("#rtu2").show();
$("#removeimg2").show();
}
}
</c:forEach>
When I keep an alert after
var g = apn;
Alert is not popped up. I have some text boxes in my UI. When I press on + icon(rendered in the form of image), another set of text boxes appear to enter multiple values. My code is not working. Can anyone help me out
I think your assignation part is incorrect. Try this -
var g = ${apn};
Seems you need an } just before /c:out. I don't know if this is the cause of your problem, i just noticed it.

Explanation of this JavaScript Code

I'm not too good on the whole JavaScript (I can do some basic validations) but this isn't my zone
I've got a piece of code below that I'm trying to understand what it does, I can read any code and understand a few parts, but this just stumped me.
Here:
function tm_search_click() {
if (document.getElementById('tm').value == 'Enter your trademark') {
document.getElementById('tm').style.backgroundColor = '#fcc';
return false;
} else {
window.location = '?tm=' + escape(document.getElementById('tm').value);
return true;
}
}
function qs(a) {
a = a.replace(/[[]/, "\[").replace(/[]]/, "\]");
var b = "[\?&]" + a + "=([^&#]*)";
var c = new RegExp(b);
var d = c.exec(window.location.href);
return d == null ? "" : decodeURIComponent(d[1]).replace(/+/g, " ")
}
if (qs("tm") != "") {
tm_trademark = document.getElementById("tm").value = unescape(qs("tm"));
tm_partner = "migu2008";
tm_frame_width = 630;
tm_frame_height = "auto";
tm_trademark_country_code = "GB";
tm_css_url = "http://remarqueble.com/api/theme/search_corporate.css";
document.getElementById("tmLoading").style.display = "block";
tm_on_search_result = function () {
document.getElementById("tmLoading").style.display = "none";
document.getElementById("tmLoaded").style.display = "block"
}
} else {
tm_search_method = "none"
}
That is all of it without the <script> tags.
Could I also edit this code so that it searches are made based on what option the user inputs?
I think it works like this (assuming that this is in tags inside html page)
Page loads.
The script checks if URL has 'tm' parameter. If it has, then it sets bunch of tm_.. parameters and callback function. I don't know how they are used.
User clicks something that triggers the tm_search_click
Script sets new URL for the page and browser starts loading that
Goto step 1.

Categories

Resources