How to Change value of input after page loads? - javascript

I have used a range picker (Progress bar) to get measurements from the customers. I have set it's limit from 1 to 50 so it takes 1 value by default if user do not select it and user can add product to the cart without selecting range picker. Is there any way that we can change by default value on page load with javascript (No jQuery) to something that does not allow user to add product to the cart.
Link: https://cutt.ly/nrB4PAR
I am using this code now but it's not working. I want value to be null.
<script type="text/javascript" language="javascript">
debugger;
var range_val = document.getElementById("tmcp_range_1").value;
if (range_val == 1)
{
document.getElementById("tmcp_range_1").value = "";
}
</script>
UPDATED:

I’m not sure I really understand why you need this, but you have to put that code in a function, then call an event listener.
function changeVal() {
var range_val = document.getElementById("tmcp_range_1").value;
if (range_val == 1) {
document.getElementById("tmcp_range_1").value = "22";
}
}
window.addEventListner("load", changeVal);

Updating the input value after DOM loads will change the value.
function updateVal() {
var range_val = document.getElementById("tmcp_range_1").value;
if (range_val == 1) {
document.getElementById("tmcp_range_1").value = "22";
}
}
window.addEventListner("load", updateVal);
And also you need to change noUiSlider logic to update UI.
Ref link https://refreshless.com/nouislider/slider-read-write/

Related

jQuery: focusout triggering before onclick for Ajax suggestion

I have a webpage I'm building where I need to be able to select 1-9 members via a dropdown, which then provides that many input fields to enter their name. Each name field has a "suggestion" div below it where an ajax-fed member list is populated. Each item in that list has an "onclick='setMember(a, b, c)'" field associated with it. Once the input field loses focus we then validate (using ajax) that the input username returns exactly 1 database entry and set the field to that entry's text and an associated hidden memberId field to that one entry's id.
The problem is: when I click on the member name in the suggestion box the lose focus triggers and it attempts to validate a name which has multiple matches, thereby clearing it out. I do want it to clear on invalid, but I don't want it to clear before the onclick of the suggestion box name.
Example:
In the example above Paul Smith would populate fine if there was only one name in the suggestion list when it lost focus, but if I tried clicking on Raphael's name in the suggestion area (that is: clicking the grey div) it would wipe out the input field first.
Here is the javascript, trimmed for brevity:
function memberList() {
var count = document.getElementById('numMembers').value;
var current = document.getElementById('listMembers').childNodes.length;
if(count >= current) {
for(var i=current; i<=count; i++) {
var memberForm = document.createElement('div');
memberForm.setAttribute('id', 'member'+i);
var memberInput = document.createElement('input');
memberInput.setAttribute('name', 'memberName'+i);
memberInput.setAttribute('id', 'memberName'+i);
memberInput.setAttribute('type', 'text');
memberInput.setAttribute('class', 'ajax-member-load');
memberInput.setAttribute('value', '');
memberForm.appendChild(memberInput);
// two other fields (the ones next to the member name) removed for brevity
document.getElementById('listMembers').appendChild(memberForm);
}
}
else if(count < current) {
for(var i=(current-1); i>count; i--) {
document.getElementById('listMembers').removeChild(document.getElementById('listMembers').lastChild);
}
}
jQuery('.ajax-member-load').each(function() {
var num = this.id.replace( /^\D+/g, '');
// Update suggestion list on key release
jQuery(this).keyup(function(event) {
update(num);
});
// Check for only one suggestion and either populate it or clear it
jQuery(this).focusout(function(event) {
var number = this.id.replace( /^\D+/g, '');
memberCheck(number);
jQuery('#member'+number+'suggestions').html("");
});
});
}
// Looks up suggestions according to the partially input member name
function update(memberNumber) {
// AJAX code here, removed for brevity
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
document.getElementById('member'+memberNumber+'suggestions').innerHTML = self.xmlHttpReq.responseText;
}
}
}
// Looks up the member by name, via ajax
// if exactly 1 match, it fills in the name and id
// otherwise the name comes back blank and the id is 0
function memberCheck(number) {
// AJAX code here, removed for brevity
if (self.xmlHttpReq.readyState == 4) {
var jsonResponse = JSON.parse(self.xmlHttpReq.responseText);
jQuery("#member"+number+"id").val(jsonResponse.id);
jQuery('#memberName'+number).val(jsonResponse.name);
}
}
}
function setMember(memberId, name, listNumber) {
jQuery("#memberName"+listNumber).val(name);
jQuery("#member"+listNumber+"id").val(memberId);
jQuery("#member"+listNumber+"suggestions").html("");
}
// Generate members form
memberList();
The suggestion divs (which are now being deleted before their onclicks and trigger) simply look like this:
<div onclick='setMember(123, "Raphael Jordan", 2)'>Raphael Jordan</div>
<div onclick='setMember(450, "Chris Raptson", 2)'>Chris Raptson</div>
Does anyone have any clue how I can solve this priority problem? I'm sure I can't be the first one with this issue, but I can't figure out what to search for to find similar questions.
Thank you!
If you use mousedown instead of click on the suggestions binding, it will occur before the blur of the input. JSFiddle.
<input type="text" />
Click
$('input').on('blur', function(e) {
console.log(e);
});
$('a').on('mousedown', function(e) {
console.log(e);
});
Or more specifically to your case:
<div onmousedown='setMember(123, "Raphael Jordan", 2)'>Raphael Jordan</div>
using onmousedown instead of onclick will call focusout event but in onmousedown event handler you can use event.preventDefault() to avoid loosing focus. This will be useful for password fields where you dont want to loose focus on input field on click of Eye icon to show/hide password

Jquery Chosen plugin. Select multiple of the same option

I'm using the chosen plugin to build multiple select input fields. See an example here: http://harvesthq.github.io/chosen/#multiple-select
The default behavior disables an option if it has already been selected. In the example above, if you were to select "Afghanistan", it would be greyed out in the drop-down menu, thus disallowing you from selecting it a second time.
I need to be able to select the same option more than once. Is there any setting in the plugin or manual override I can add that will allow for this?
I created a version of chosen that allows you to select the same item multiple times, and even sends those multiple entries to the server as POST variables. Here's how you can do it (fairly easily, I think):
(Tip: Use a search function in chosen.jquery.js to find these lines)
Change:
this.is_multiple = this.form_field.multiple;
To:
this.is_multiple = this.form_field.multiple;
this.allows_duplicates = this.options.allow_duplicates;
Change:
classes.push("result-selected");
To:
if (this.allows_duplicates) {
classes.push("active-result");
} else {
classes.push("result-selected");
}
Change:
this.form_field.options[item.options_index].selected = true;
To:
if (this.allows_duplicates && this.form_field.options[item.options_index].selected == true) {
$('<input>').attr({type:'hidden',name:this.form_field.name,value:this.form_field.options[item.options_index].value}).appendTo($(this.form_field).parent());
} else {
this.form_field.options[item.options_index].selected = true;
}
Then, when calling chosen(), make sure to include the allows_duplicates option:
$("mySelect").chosen({allow_duplicates: true})
For a workaround, use the below code on each selection (in select event) or while popup opened:
$(".chosen-results .result-selected").addClass("active-result").removeClass("result-selected");
The above code removes the result-selected class and added the active-result class on the li items. So each selected item is considered as the active result, now you can select that item again.
#adam's Answer is working very well but doesn't cover the situation that someone wants to delete some options.
So to have this functionality, alongside with Adam's tweaks you need to add this code too at:
Chosen.prototype.result_deselect = function (pos) {
var result_data;
result_data = this.results_data[pos];
// If config duplicates is enabled
if (this.allows_duplicates) {
//find fields name
var $nameField = $(this.form_field).attr('name');
// search for hidden input with same name and value of the one we are trying to delete
var $duplicateVals = $('input[type="hidden"][name="' + $nameField + '"][value="' + this.form_field.options[result_data.options_index].value + '"]');
//if we find one. we delete it and stop the rest of the function
if ($duplicateVals.length > 0) {
$duplicateVals[0].remove();
return true;
}
}
....

Can't get sessionStorage to work correctly

I have multiple buttons that when they are clicked an image is loaded and the image is supposed to stay there based even when the page refreshes. When I use this the button with the highest setItem value always shows even if I click on other button. How do I fix this?
here is one of the scripts:
<script type="text/javascript">
var isImage1 = sessionStorage.getItem('2');
function showImage1() {
sessionStorage.setItem('isImage1', '2');
$("#loadingImage1").show();
$("#loadingImage").hide();
$("#loadingImage2").hide();
$("#loadingImage3").hide();
$("#loadingImage4").hide();
$("#loadingImage5").hide();
$("#loadingImage6").hide();
}
if(isImage1 == 2) showImage1();
</script>
and here is one of my buttons:
<input name="EPL/MECH DESIGN - TECHS" style="white-space:normal"
onclick="moveText(this.name);showImage1();form1.submit()"
style="width: 275px" type="button" value="7SBD EPL/Mech. Design Techs" />
Update: I have updated this line
var isImage1 = sessionStorage.getItem('2');
to
var isImage1 = sessionStorage.getItem('isIamge1');
but my issue still exists, that the isImage with the largest value stays even when i click the other buttons, so help is still needed.
In your session storage, you are setting the value of the 'isImage1' Item to '2'
sessionStorage.setItem('isImage1', '2');
But in your code to retrieve the value you are actually retrieving the item '2'
var isImage1 = sessionStorage.getItem('2');
You need to change your sessionStorage.getItem to reference 'isImage1'
var isImage1 = sessionStorage.getItem('isImage1');
Then you should get the value you are expecting.
There are loads of good jsfiddles on session storage. you may get some ideas from this one:
http://jsfiddle.net/gabrieleromanato/XLRAH/
Incidently; this is a very small value you are storing, why not store it in a cookie instead?
EDIT:
based on the fact that you have multiple functions exactly like this one, you are better off following Ken's solution, the only thing I would add is a wildcard to turn off the other images:
function showImage(imgNum) {
sessionStorage.setItem('Image',imgNum);
$("[id^=loadingImage]").hide();
$("#loadingImage" + imgNum).show();
}
showImage(sessionStorage.getItem('Image'));
The code in the buttons would then be showImage(1) instead of showImage1();
_Pez
By re-factoring the code a little you can do something like this:
/// setup some vars including max number of images
var maxImages = 6, i = 1, v;
/// now loop through and get the items for each image
for(; i =< maxImages; i++) {
v = sessionStorage.getItem('isImage' + i);
/// if in storage, call show image with the number to show
if (v !== null) showImage(i);
}
/// show image based on number
function showImage(num) {
sessionStorage.setItem('isImage' + num, '1');
$("#loadingImage" + num).show();
}
Also note that sessionStorage only deals with strings. So in order to check a specific number you need to convert it to one first parseInt(value, 10);.
But in this case the 1 that we set can be anything - it's just to store some value so sessionStorage doesn't return null.
In the button code you can change it to do this:
<input name="EPL/MECH DESIGN - TECHS" style="white-space:normal"
onclick="moveText(this.name);showImage(1);form1.submit()"
style="width: 275px" type="button" value="7SBD EPL/Mech. Design Techs" />

JavaScript textfield validation: sending focus back

I am using JQuery and JavaScript for an input form for time values, and I can't make JavaScript to provide the intended reaction to incorrect input format.
What do I do wrong...?
I have a set of 3 text inputs with class "azeit" (and under these a number of others of class "projekt"). All are used to input time values. As soon as the user exits the field I validate the format, do a calculation with it and display the result of this in a field with id "summe1". This works. If the format is incorrect, I display an alert and what I want to do is return the focus to the field after emptying it. However, the focus never gets returned (although it will get emptied all right). This is it:
var kalkuliere_azeit = function(e) {
var anf = $("#anfang");
var ende = $("#ende");
var pause = $("#pause");
var dauer_in_min = 0;
var ungueltiges = null;
if (nonempty(anf.val(), ende.val()), pause.val()))
{
if (!is_valid_date(make_date(anf.val()))){
ungueltiges = anf;
};
if (!is_valid_date(make_date(ende.val()))){
ungueltiges = ende;
};
if (!is_valid_date(make_date(pause.val()))){
ungueltiges = pause;
};
if (ungueltiges)
{
alert("invalid time"); //This is where I am stuck
ungueltiges.val("");
ungueltiges.focus();
}
else {
dauer_in_min = hourstring_to_min(ende.val())
- hourstring_to_min(anf.val())
- hourstring_to_min(pause.val());
$("#summe1").text(min_to_hhmm(dauer_in_min));
};
};
};
....
$(document).ready(function() {
$(".projekt").change( kalkuliere_summe);
$(".azeit").focusout(kalkuliere_azeit);
});
The fields with the class "projekt" are below those with the class "azeit" so they'll get the focus when the user leaves the third field of class "azeit".
I apologize for supplying incomplete source code. I hope someone can see what's wrong.
One point I'd like to mention is that I tried binding the handler to onblur and onfocus as well. When I bind it to onfocus the focus does get reset to the field, but the last field the user enters will not update the field $("#summe1") correctly (because this would need focusing another field of the same class).
Im not sure whats wrong with your code but one way of doing it would be to put the focus into a function.
So ...
function focusIt()
{
var mytext = document.getElementById("divId");
mytext.val("");
mytext.focus();
}
And call it from the if/else statement ...
if (ungueltiges)
{
alert("invalid time");
focusIt()
}

How do I use the Yahoo YUI to do inline cell editing that writes to a database?

So I have datatable setup using the YUI 2.0. And for one of my column definitions, I've set it up so when you click on a cell, a set of radio button options pops so you can modify that cell content.
I want whatever changes are made to be reflected in the database. So I subscribe to a radioClickEvent. Here is my code for that:
Ex.myDataTable.subscribe("radioClickEvent", function(oArgs){
// hold the change for now
YAHOO.util.Event.preventDefault(oArgs.event);
// block the user from doing anything
this.disable();
// Read all we need
var elCheckbox = oArgs.target,
newValue = elCheckbox.checked,
record = this.getRecord(elCheckbox),
column = this.getColumn(elCheckbox),
oldValue = record.getData(column.key),
recordIndex = this.getRecordIndex(record),
session_code = record.getData(\'session_code\');
alert(newValue);
// check against server
YAHOO.util.Connect.asyncRequest(
"GET",
"inlineeddit.php?sesscode=session_code&",
{
success:function(o) {
alert("good");
var r = YAHOO.lang.JSON.parse(o.responseText);
if (r.replyCode == 200) {
// If Ok, do the change
var data = record.getData();
data[column.key] = newValue;
this.updateRow(recordIndex,data);
} else {
alert(r.replyText);
}
// unblock the interface
this.undisable();
},
failure:function(o) {
alert("bad");
//alert(o.statusText);
this.undisable();
},
scope:this
}
);
});
Ex.myDataTable.subscribe("cellClickEvent", Ex.myDataTable.onEventShowCellEditor);
But when I run my code and I click on a cell and I click a radio button, nothing happens ever. I've been looking at this for some time and I have no idea what I'm doing wrong. I know you can also use asyncsubmitter within my column definition I believe and I tried that, but that also wasn't working for me.
Any ideas would be greatly appreciated.

Categories

Resources