MaterializeCss Use dblclick event to open datepicker modal - javascript

I'm working with materializecss and my boss asked me to change the trigger on the datepicker modal from the classic 'click' to a double click.
Problem is, there's no documentation about that, and maybe is hard-coded in the object.
Is there a way to change this behavior?

You can create two input elements and hide either of them. Below I've created input1 as a datepicker and input2 as a standard text input. Then I've hidden the first one and assigned an event listener (ondblclick) for the second one.
It may not be the best solution but works.
var datepicker = document.querySelector('#input1')
var input2 = document.querySelector('#input2')
var options = {
autoClose : true,
container : document.body,
onSelect : function (day) {
input2.value = day.toDateString(),
M.updateTextFields()
}
}
var instance = M.Datepicker.init(datepicker, options)
input2.ondblclick = function () {
instance.open()
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<div class="row">
<div class="input-field col s5 hide">
<input type="text" class="datepicker" id="input1">
</div>
<div id="div2" class="input-field col s5">
<input type="text" id="input2">
<label for="input2">Pick a date</label>
</div>
</div>

Related

How to checkbox enable/disable with Struts 2

I would like to show 2 checkboxs in my page (called box1 and box2). The default value is box1 = false and box2 = false. But I also have to enable box2 only if box1 = true. So I have created the following JS function :
function myTest() {
var check = document.getElementById('box1');
if (check.checked == false) {
$('#box2').prop('disabled', true);
} else {
$('#box2').prop('disabled', false);
}
}
Now I don't really understand how to use myTest function in the JSP file. I have tried to use it with onload="myTest()" as follow, but it doesn't work (box2 is always disabled).
<body onload="myTest()" />
<div class="form-group row">
<label class="col-sm-3 col-form-label required">
<s:text name="box1" />
</label>
<div class="col-sm-9">
<s:checkbox id="box1" name="box1"> </s:checkbox>
</div>
</div>
<div class="form-group row">
<label class="col-sm-3 col-form-label required">
<s:text name="box2" />
</label>
<div class="col-sm-9">
<s:checkbox id="box2" name="box2"></s:checkbox>
</div>
</div>
It seems you are using jQuery in the page. Here is my solution.
<script type="text/javascript">
$( document ).ready(function() {
// on page load unchecking and disabling box2
$("#box2").prop("checked", false);
$("#box2").prop("disabled", true);
});
$("#box1").on("change", function(){
if ($(this).prop("checked")){
// box1 is checked
$("#box2").prop("disabled", false);
}
else{
// box1 is not checked
$("#box2").prop("checked", false);
$("#box2").prop("disabled", true);
}
});
</script>
There is onchange attribute for <s:checkbox> tag which is used for
Set the html onchange attribute on rendered html element
This tag generates a simple input field of checkbox type.
Renders an HTML input element of type checkbox, populated by the specified property from the ValueStack.
The action bean is on top of the ValueStack, so you can get the specified property there.
To define JS function in JSP you should use html <script> tag. You can do it in the <head> tag or after the rendered element.
<s:checkbox id="box1" name="box1" onchange="myTest()"/>
<s:checkbox id="box2" name="box2" %{box1?'':'disabled="disabled"'}/>
<script>
function myTest() {
if ($(this).prop("checked") === "checked") {
$("#box2").removeAttr("disabled");
} else {
$("#box2").attr("disabled","disabled");
}
}
</script>

Selecting a default radio input on page load Javascript

I have a page that when I change radio boxes it shows different content.
It works when I click radio boxes. But in an edit form, I would like the second radio option to be selected and content of second radio option to be shown on page load. The content is not shown when I populate 'checked' on the radio as shown in the demo.
Demo.
var aTag = document.querySelector("a.mylink");
aTag.addEventListener("click", function(e) {
e.preventDefault();
var query = document.querySelector("input[data-for='" + e.currentTarget.id + "']").value;
window.open(e.currentTarget.href + "?query=" + query, "_blank");
}, false);
// radio element click event handler
var radioClickHandler = function() {
var first = document.querySelector('.first');
var second = document.querySelector('.second');
second.classList.add('hidden');
// show/hide required elements depending on which radio element was clicked.
if (this.value == 'product') {
first.classList.remove('hidden');
second.classList.add('hidden');
}
if (this.value == 'keyword') {
first.classList.add('hidden');
second.classList.remove('hidden');
}
}
// Get All Radio Elements
var radios = document.querySelectorAll('[type=radio]');
// Apply click event
for (var i = 0; i < radios.length; i++) {
radios[i].addEventListener('click', radioClickHandler);
}
// Apply Default
radioClickHandler.apply(radios[0]);
.hidden {
display: none;
}
<div class="col-md-8 offset-md-2">
<div class="m-form__group form-group row">
<div class="col-9">
<div class="m-radio-inline mt-3 type_selector">
<label class="m-radio">
<input type="radio" name="type" value="product" data-id="specific_product"> First
<span></span>
</label>
<label class="m-radio">
<input type="radio" name="type" value="keyword" required="" data-id="search_term" checked> Second
<span></span>
</label>
</div>
</div>
</div>
<style>
/*hides element*/
</style>
<div class="first">
<label for="" class="mt-2 mb-2"><strong>First Content</strong></label>
<select class="form-control m-select2 select2-hidden-accessible" id="m_select2_1" name="product_id" data-select2-id="m_select2_1" tabindex="-1" aria-hidden="true">
<option value="" data-select2-id="" disabled selected>Blabla
</option>
</select>
</div>
<div class="second">
<label for="exampleInputEmail1" class="pt-3"><strong>Second Content</strong></label>
<div class="row mt-1 ">
<div class="col-xl-8">
<input type="text" class="form-control m-input m-input--solid" data-for="search_term" name="{{$default_template->notification_toggle_id}}_search_term" value="" id="m_autosize_1" placeholder="blabla">
</div>
<div class="col-xl-4 align-self-center">
First Content
<script>
</script>
</div>
</div>
</div>
<script type="text/javascript">
</script>
</div>
I tried several things like. But I couldn't succeed.
window.onload = radioClickHandler;
After
window.onload = function() {
The whole javascript snippet
};
Also this
var radios = document.querySelectorAll('.type_selector .m-radio input[type=radio]');
Working fiddle.
You could simply invoke the click event using :
radios[1].click();
Edit:
The problem happens since you're attaching the click event to all the radio button in the current document in the following line :
var radios = document.querySelectorAll('[type=radio]');
To fix this issue you need to encapsulate the first & second radios so you could attach the click to them separately :
<div id="first-second" class="m-form__group form-group row">
Then attach the event just to them like :
var radios = document.querySelectorAll('#first-second [type=radio]');
The onchange or onclick event does not fire when the selected option of the select object is changed programmatically or you fill the input value programmatically. So you do require to trigger that onchange or onclick after changing it in window.onload or init function.
To trigger the event use How to trigger event in JavaScript?
EDIT: I think it is the addition of the other radio buttons are being added to the same group so second is not your second radio but 5th so this will now work
radioClickHandler.apply(radios[5]);
http://jsfiddle.net/wy9xbhdo/

how to generate the id of a div dynamically using javascript

I have a (+) sign and a (-) sign. If the user clicks on the + sign than whatever their in the row will automatically get generated the same with new id.
Now when user click on + sign than div id and text box under it will get changed.
Code below for div as follows:
<div class="row" id="Div0">
<div class="col-md-3">
<div class="form-group">
<label for="name">Last Name</label>
<input type="text" class="form-control" id="txtLastName0" placeholder="Enter name" required="required" />
</div>
</div>
<div class="col-md-9"></div>
</div>
Now when user clicks on + sign the new row with text box with new id txtLastName1 will get generated.
Now on click of + sign how do i get new id of textbox and a div with new row.
Div1 and textbox1 will get generated
Basically what you should do is, keep the markup you want to generate as a template in your DOM and when user clicks the "Add" button, clone this markup and append to the DOM (to a container div). then update the Id's of the input and divs as needed.
A simply sample would be like
<div class="row" id="template" style="display: none;">
<div class="col-md-3">
<div class="form-group">
<label for="name">Last Name</label>
<input type="text" class="form-control lname" id="txtLastName"
placeholder="Enter name" required="required" />
</div>
</div>
<div class="col-md-9"></div>
</div>
<button id="btnAdd">+</button>
<div id="container"></div>
Now wire up a click event handler to the Add/+ button. You may use the jQuery clone() method.
$(function () {
$("#btnAdd").click(function(e) {
e.preventDefault();
var childCount = $("#container").children().length;
var c = $("#template").clone().show();
c.attr("id", "Div" + childCount );
c.find(".lname").attr('id', 'txtLastName' + childCount);
$("#container").append(c);
});
});
For deleting, you can add a event handler on the delete button and remove the specific div from dom. jQuery remove() method will do it. Use closest() and find as needed to get the correct div to remove.
Here is a working simple jsbin sample for your reference

How to display number in input field's to currency format in bootstrap addon?

I'm working on small web form where I need to display number in the text field's as currency format in bootstrap appended addon.
I'm able to achieve for a single field using jQuery selectors (I'm new to Javascript world), I wanted to do the same thing for aroung 10 fields.
I think there must be elegant solution rather than writing the same for every field.
Kindly help me.
My HTML Code:
<div class="control-group">
<label class="control-label">Loan Amount 1</label>
<div class="controls">
<div class="input-append">
<input class="span2" id="loanAmount1" type="text">
<span class="add-on" id="loanAmount1Cur">$</span>
</div>
</div>
</div>
<div class="control-group">
<label class="control-label">Loan Amount 2</label>
<div class="controls">
<div class="input-append">
<input class="span2" name="loanAmount2" type="text">
<span class="add-on" name="LoanAmount2Cur">$</span>
</div>
</div>
</div>
My JS Code:
$(document).ready(function () {
$("#loanAmount1").on("keyup", null, function () {
var input = $("#loanAmount1").val();
var num = parseFloat(input).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,') + " $";
$("#loanAmount1Cur").html(num);
});
});
My JSFiddle: http://jsfiddle.net/kiranm516/me52djL8/24/
I copied the above code from (thanks to them): Add comma to numbers every three digits
Assign a class to your inputs, and then bind the keyup event to your class, rather than to an ID.
Forked your JSFiddle: http://jsfiddle.net/zmbh4o2u/
JS:
$(document).ready(function () {
$(".loan-input").on("keyup", null, function () {
var $input = $(this),
value = $input.val(),
num = parseFloat(value).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
$input.siblings('.add-on').text('$' + num);
});
});
Helpful tips:
In the handler function for your keyup event, you can access the element that fired the event with this. Since you'll need that element a couple of times, it's customary to cache a jQuery object in a local var, hence var $input = $(this).
When declaring multiple variables in JavaScript, it's best practice to chain them in a single var statement. You can comma separate your declarations, and use line breaks for legibility.

Linking two bootstrap timepicker input elements

I am trying to implement two dropdown menus: one for a time value, and one for a duration starting from that time onwards. i.e something like this.
I am using a bootstrap timepicker for the dropdown menu.
I wrote this method for the first field:
$('#timeWithDuration')
.timepicker({ 'scrollDefaultNow': true })
.on('change', function() {
var from_time = $("input[name='from_time']").val();
$('#duration').timepicker({
'minTime': from_time,
'maxTime': '11:30pm',
'showDuration': true
});
});
where #timeWithDuration is my first input field and #duration is my second. This works fine the first time I do it (after selecting a value in the first field, I can only see times past that value in the second field) but it then doesn't let me update the values anymore. i.e I can't select a new value for neither the first, nor the second field. The dropdown displays properly, but then doesn't update the value on select.
This is the HTML code for the input fields:
<div class='col-sm-5'>
<input id='timeWithDuration' type='text' class='form-control ui-timepicker-input' name='from_time' placeholder='What time?' autocomplete='off'>
</div>
<div class='col-sm-5'>
<input id='duration' type='text' class='form-control ui-timepicker-input' placeholder='Duration' autocomplete='off'>
</div>
Unexperienced frontend dev here so please be gentle <3 Cheers!
Use the proper event changeTime and reset the duration input every time:
DEMO: JSnippet
HTML:
<div class='row'>
<div class='col-sm-5'>
<input id='timeWithDuration' type='text' class='form-control ui-timepicker-input' name='from_time' placeholder='What time?' autocomplete='off'>
</div>
<div class='col-sm-5'>
<input id='duration' type='text' class='form-control' placeholder='Duration' autocomplete='off'>
</div>
</div>
JS:
$(function() {
var $duration = $('#duration');
var $timeWithDuration = $('#timeWithDuration');
$timeWithDuration
.timepicker({ 'scrollDefaultNow': true })
.on('changeTime', function() {
var from_time = $("input[name='from_time']").val();
if ($duration.hasClass('ui-timepicker-input')) {
$duration.timepicker('remove');
$duration.val('');
}
$duration.timepicker({
'minTime': from_time,
'maxTime': '11:30pm',
'showDuration': true
});
});
});
Looks like you are using this timepicker.
You will want to create an onchange event on the #timeWithDuration input that updates the minTime option on your timepicker.
Also, I would initialize your second timepicker outside of your onchange event for the first.
$('#timeWithDuration')
.timepicker({ 'scrollDefaultNow': true })
.on('changeTime', function() {
var from_time = $("input[name='from_time']").val();
$('#duration').timepicker('option', 'minTime', from_time);
if ($('#duration').val() && $('#duration').val() < from_time) {
$('#duration').timepicker('setTime', from_time);
}
});
$('#duration').timepicker({'maxTime': '11:30pm', 'showDuration': true});
<link href="https://rawgit.com/jonthornton/jquery-timepicker/master/jquery.timepicker.css" rel="stylesheet"/>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/jonthornton/jquery-timepicker/master/jquery.timepicker.min.js"></script>
<div class="col-sm-5">
<input id="timeWithDuration" type="text" class="form-control ui-timepicker-input" name="from_time" placeholder="What time?" autocomplete="off">
</div>
<div class="col-sm-5">
<input id="duration" type="text" class="form-control ui-timepicker-input" placeholder="Duration" autocomplete="off">
</div>
As #Shlomi Hassid pointed out in his answer, you would also want to use the timepicker's changeTime event, rather than the native change event, so that the function will only execute when the input in your #timeWithDuration timepicker is a valid time.

Categories