Change text label where inside there are an input checkbox element - javascript

I have this part of html on my form:
<label class="ideal-radiocheck-label" onclick="">
<input id="pagamento_8" class="_input " type="checkbox" onclick="half(this,value);" checked="" value="980" name="pagamento[]" style="position: absolute; left: -9999px;" autocomplete="off">
<span class="ideal-check checked"></span>
988 (980-980 €)
</label>
It is a checkbox input button that call the function half() to make something like call the next function:
function setClickedLabel(clicked,new_value){
label_e=$(clicked).parent();
label_t=$(label_e).text();
labels_t=label_t.split('-');
$(label_e).html(labels_t[0]+'-'+new_value+' €)'); <-- 1
//$(label_e).text(labels_t[0]+'-'+new_value+' €)'); <-- 2
//$(label_e).innerHTML = labels_t[0]+'-'+new_value+' €)'; <-- 3
}
Here i would change a part of the label "988 (980-980 €)" (the last 980) and the "clicked" variable is the input object that you can see inside the label element.
Using one of the three methods reported i got 2 effect. Whit 1,2 it changes the label but it removes the input element. Whit 3 it doesn't make nothing.
What function i can use? How i must fix the code to get what i need?
Html can't be changed.
Maybe another alternative without appending.
tnx,
j.

Adapting the script on jsfindle left on the comment from adeneo i have wrote that solution. Maybe can be other better solutions.
function setClickedLabel(clicked,new_value,old_value){
label = $(clicked).parent().contents().filter(function() {
return this.nodeType === 3 && this.nodeValue.trim().length;
}).get(0);
label.nodeValue = label.nodeValue.replace(new RegExp("-"+old_value), "-"+new_value);
}

Related

Show hide/div based on drop down value at page load

I have the following code that I use to hide/show a div using a drop-down. If the Value of the drop-down is 1, I show the div, otherwise I hide it.
var pattern = jQuery('#pattern');
var select = pattern.value;
pattern.change(function () {
if ($(this).val() == '1') {
$('#hours').show();
}
else $('hours').hide();
});
The select drop down retrieves its value from the database using form model binding:
<div class="form-group">
<label for="pattern" class="col-sm-5 control-label">Pattern <span class="required">*</span></label>
<div class="col-sm-6">
{{Form::select('pattern',['0'=> 'Pattern 0','1'=> 'Pattern 1'],null,
['id'=>'pattern','class' => 'select-block-level chzn-select'])}}
</div>
</div>
This select drop-down then hides or shows the following div:
<div id="hours" style="border-radius:15px;border: dotted;" >
<p>Example text</p>
</div>
The problem:
The div won't be hidden if the pattern stored in the database is set to 0. I have to manually select "Pattern 0" from the drop down to change it. I know that is due to the .change() method. But how do I make it hide/show on page load?
Usually in such case I store the anonymous function reference as below:
var checkPattern = function () {
if ($('#pattern').val() == '1') {
$('#hours').show();
}
else $('#hours').hide();
}
It makes the code ready to use in more then one place.
Now your issue could be resolve in a more elegant way:
$(document).ready(function(){
// add event handler
$('#pattern').on('change', checkPattern);
// call to adjust div
checkPattern();
});
Well, if the element "should" be visible by default, you just then have to check condition to "hide it" (you don't have to SHOW an element that is already visible...) :
if(pattern.value != %WHATEVER%) { $('#hours').toggle(); }
Then, to switch display on event or condition or whatever :
pattern.change(function(evt){
$('#hours').toggle();
});
Not sure that your event will work. I'd try something like
$(document).on(..., function(evt){
//behaviour
});
http://api.jquery.com/toggle/
https://learn.jquery.com/events/handling-events/

Show div on checkbox check and hide it when unchecked (even on load because localstorage)

So the page must show a div if a checkbox is checked, and hide it when it is unchecked. But I am using localstorage so it shouldn't hide on load of the page but only when it is unchecked. If it is possible, it should be usable for a lot of checkboxes (37 exactly).
My Code:
HTML:
<div id="mob1-div" class="row hide one">Mobilisern1</div>
<div id="mob2-div" class="row hide-div">Mobilisern2</div>
<div id="mob1" class="targetDiv">Mobiliseren 1<input type="checkbox" class="checkbox chk" value="one" data-ptag="mob1-div" store="checkbox1"/></div>
<div id="mob2" class="targetDiv">Mobiliseren 2<input type="checkbox" class="checkbox" data-ptag="mob2-div" store="checkbox2"/></div>
Javascript:
$(function() {
var boxes = document.querySelectorAll("input[type='checkbox']");
for (var i = 0; i < boxes.length; i++) {
var box = boxes[i];
if (box.hasAttribute("store")) {
setupBox(box);
}
}
function setupBox(box) {
var storageId = box.getAttribute("store");
var oldVal = localStorage.getItem(storageId);
console.log(oldVal);
box.checked = oldVal === "true" ? true : false;
box.addEventListener("change", function() {
localStorage.setItem(storageId, this.checked);
});
}
});
$(function(){
$(".chk").on('change',function(){
var self=$(this);
var aData= self.attr("value");
$("."+aData).toggleClass('hide')
});
});
The problem with this code is that when you check the box the div shows, but if you reload the page the box is still checked. Although, the div isn't visible anymore.
Your issue seems to be centered around the fact that your second checkbox did not specify a value attribute (which all checkboxes need to have for them to make any sense).
I made a few adjustments to your code to make it more valid and compact (replaced store with data-store, used a ternary operator instead of if/then, combined the two document.ready functions into one, and changed your for loop to a forEach). These changes aren't part of the issue, but they do allow for your code to be more brief, which aids in troubleshooting.
localStorage doesn't work in the Stack Overflow snippets, but a working version can be seen in this Fiddle.

Check input elements responsively when changed

I have this code. It obviously calls function when selected element is focused. The function then checks if selected element has length less than 3, and if it does it changes background color of the element.
$('#register-form input[type="text"]').focus(function(){
if ($(this).length < 3) {
$(this).css('background','#f00');
}
});
Now the problem is that when there are more than 4 characters within input, color still remains. The problem is that it calls function when element is focused. After that, it doesn't check the if statement anymore, as obviosuly function is never called again.
The solution I seek; I want it to check if the IF statement is still legit once the input element value is changed. Or any other smooth way to check IF statements and calls functions in a live time.
The answer to this question is simple and well known. However, as you answer please provide some information related to this question; What are the best ways to check various changes in statements lively? What are the best ways to make website 'alive' and respond to any actions immediately?
Give the error a class and use onkeyup (and change if you wish - which triggers on blur too)
Also test the .val().length instead:
<style>
.error { background-color:red }
</style>
$('#register-form input[type="text"]').on("keyup,change",function(){
$(this).toggleClass("error", $(this).val().length < 3);
}).keyup(); // trigger on load
$(function() {
$('#register_form input[type="text"]').on("keyup", function() {
$(this).toggleClass("error", $(this).val().length < 3);
console.log("error")
}).keyup(); // initialise in case of reload
});
.error {
color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="register_form">
<input type="text" />
<input type="text" />
<input type="text" />
</form>
Try this:
$('#register-form input[type="text"]').on("focus input", function(){
$(this).css('background', $(this).val().length < 3 ? '#f00' : '#fff');
});
EDIT
Personally, I use AngularJS alot for web applications that have alot of these. E.g. you can do this:
<input type="text" ng-model="myValue" ng-style="{'background-color', myValue.length < 3 ? '#f00' : '#fff'}"/>

Block btn until at least 1 checkbox of an offset is selected

A little frustrated here, somehow I can't make this work no matter what I try. I have a small form with 2 offsets, each containing a few checkboxes as the following:
<input type="checkbox" id="test1" /><label for="test1">
I need to make sure the user selects at least one of them in each offset in order to be able to click this button, otherwise it should be unclickable :)
<div class="offset6">
<a class="btn btn-warning" href="#openModal">CONTINUAR<span class="btn_caret"></a>
</span></button>
</div>
This should work for you:
//listen for changes to any checkbox so we can re-evaluate the button state
$("input[type='checkbox']").change(function(){
validateInput();
});
//checks to see if the button should be enabled or not
function validateInput(){
//get the count of checked items in each of the offsets
var offset3Count = $(".offset3").find("input[type='checkbox']:checked").length;
var offset8Count = $(".offset8").find("input[type='checkbox']:checked").length;
//set the disabled state of the button based on the offset counts
$(".btn").prop("disabled", offset3Count == 0 || offset8Count == 0);
}
//call the function on page load to ensure the button is initially disabled
validateInput();
Here is a working example (I had to change your HTML a bit as it was invalid)
If you need a specific .btn, as in the one in offset6, then use this line instead:
$(".offset6 .btn").prop("disabled", offset3Count == 0 || offset8Count == 0);
Here is the example
A quick recommendation: If you have unique elements then consider using an id attribute for them. For example:
<button id="btn6" ...>
With the following JQuery selector:
$("#btn6")...
Try
var chk = $(".offset3,.offset8").find('input[type="checkbox"]'); //cache your selector
chk.change(function () {
$('div.offset6 a.btn.btn-warning[href="#openModal"]').prop('disabled', chk.filter(':checked').length);
});
chk.filter(':checked').length get length of checked checboxes
$('.btn').prop('disabled', $('input[type="checkbox"]:checked').length);
Updated After OP's Comment
$('div.offset6 a.btn.btn-warning[href="#openModal"]').prop('disabled', $('input[type="checkbox"]:checked').length);
or add and id to than use # id-selector

Updating elements with jQuery selector

I have a situation where I have the following form elements:
<label for="edit-type-config-associated-element--2">Destination Data Element </label>
<input type="text" id="edit-type-config-associated-element--2"
name="type_config[associated_element]" value="23" size="60"
maxlength="128" class="form-text ajax-processed"
style="visibility: hidden;">
<input type="text" id="edit-type-config-associated-element--2_display"
value="23" size="60" maxlength="128"
class="form-text ajax-processed dropdowntree_aux dropdowntree_input valid"
readonly="" style="top: 61.515625px; left: 15px; position: absolute;
width: 389px; height: 16px;">
I would like to add a change listener to the second input element (identified by edit-type-config-associated-element--2_display) and then change the input in the first input element (identified by edit-type-config-associated-element--2). The catch here is that everytime this form is displayed the number appearing at the end of both ids increments by one (why they couldn't use a consistent id, I have no idea but it is what I am stuck with).
Here is the javascript I am using to try and accomplish this:
// Add a change listener to associated element link for dc mappings
$('.dropdowntree_input').live('change', function () {
// Get the data element id
var dataElementID = $.trim($(this).val()),
dataElementLinks = Drupal.settings.data_element_links;
console.log('text field has changed to: ' + dataElementID);
if (dataElementLinks.hasOwnProperty(dataElementID)) {
$('#linked_form_elements').show();
} else {
$('#linked_form_elements').hide();
}
// Update the underlying text input to contain the right value.
$(':input[type="text"][name="type_config[associated_element]"]').val(dataElementID);
However this is not working. It seems that this function is never called when the second textfield is updated.
Any ideas where I have gone off the rails?
Thanks.
Looks like you were missing a [ in your selector
$('input[type="text"][name="type_config[associated_element]"]').val(dataElementID);
^ here
Also if you are using jQuery >= 1.9 then .live() is no longer supported.
If you are using jQuery >= 1.7 then use .on() instead, also since the first and second inputs are next/prev siblings you can use that relationship to find the element
$(document).on('change', '.dropdowntree_input', function () {
var dataElementID = $.trim($(this).val()),
dataElementLinks = Drupal.settings.data_element_links;
console.log('text field has changed to: ' + dataElementID);
if (dataElementLinks.hasOwnProperty(dataElementID)) {
$('#linked_form_elements').show();
} else {
$('#linked_form_elements').hide();
}
//since the hidden element is the previous sibling
$(this).prev().val(dataElementID);
})

Categories

Resources