How to wrap two elements into one div? - javascript

I have a problem with wrapping two elements: label and input into one div. Can you help me how to do it right ? Thank you very much.
Example:
<label><label>
<input>
<label></label>
<input>
Should be:
<div data-role="fieldcontain">
<label><label>
<input>
</div>
<div data-role="fieldcontain">
<label><label>
<input>
</div>
Jquery:
$('input[type="text"]').prev().andSelf().wrap('<div data-role="fieldcontain">');
HTML:
<label>Name: </label>
<input type="text" name="name" id="name" value="" />
<label>Surname: </label>
<input type="text" name="surname" id="surname" value="" />

You need to loop through each input then club the input and the label and use .wrapAll() like
$('input[type="text"]').each(function () {
$(this).prev().addBack().wrapAll('<div data-role="fieldcontain">');
})
Demo: Fiddle

Related

how can i make the input text display in the textfield?

I want this input project name and address displayed in the text area.
currently, the input project name and checkbox text can be displayed in the textbox.
ps: I forgot to add checkbox HTML codes in the previous question.
I would appreciate your help.
here is my code:
let existValue = "";
$('input:checkbox').click(function(){
var tb = "#"+$(this).attr('rel');
let text_to_add = this.name + "\n";
let inputVal = $('#pname').val()
//when click a checkbox and show checked items in the text area
if($(this).is(":checked")){
$(tb).val($(tb).val() + text_to_add);
}else{
let remove = this.name +"\n";
//when a box is unchecked it clears the previously populated text from checkbox
$(tb).val($(tb).val().replace(remove,""));
}
//storing the value to existValue
existValue = $(tb).val().replace(`${inputVal}\n`, "");
});
$('#pname').on('input',(e)=>{
//here to adding the input value to the existValue
$('#textbox1').val(`${e.target.value}\n${existValue}`)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="name">
<form>
<label for="projectname">Project name:</label>
<input type="text" id="pname" name="pname">
<br>
<div class="form-group">
<label>Project Address:</label>
<input type="text" class="form-control" id="search_input" placeholder="Type address..." />
<input type="hidden" id="loc_lat" />
<input type="hidden" id="loc_long" />
</div>
<div class="latlong-view">
<p><b>Latitude:</b> <span id="latitude_view"></span></p>
<p><b>Longitude:</b> <span id="longitude_view"></span></p>
</div>
</div>
<div class="series1">
<tr><input type="checkbox" rel="textbox1" name="Cabinets" class=test/>
Cabinets
</tr>
<input type="checkbox" rel="textbox1" name="Doors"/>
Doors
<input type="checkbox" rel="textbox1" name="Drawers">
Drawers
<input type="checkbox" rel="textbox1" name="Drawer Fronts">
Drawer Fronts
<input type="checkbox" rel="textbox1" name="Handles">
Handles
</div>
<br>
<textarea id="textbox1" ></textarea>
This should do it:
const inps=$('input[type=text]').on('input',()=>
$('#textbox1').val(inps.get().map(i=>i.value).join("\n"))
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="name">
<form>
<label for="projectname">Project name:</label>
<input type="text" id="pname" name="pname">
<br>
<div class="form-group">
<label>Project Address:</label>
<input type="text" class="form-control" id="search_input" placeholder="Type address..." />
<input type="hidden" id="loc_lat" />
<input type="hidden" id="loc_long" />
</div>
<div class="latlong-view">
<p><b>Latitude:</b> <span id="latitude_view"></span></p>
<p><b>Longitude:</b> <span id="longitude_view"></span></p>
</div>
</div>
<textarea id="textbox1"></textarea>
As there are no checkboxes in your current HTML I removed the event handling for these elements and concentrated on the text-inputs. In my snippet I selected the input fields by their type (=text). In a real example you should apply a common class to them and select them through that.

Display two fields as mandatory based on selected radio button

I have this radio button in HTML.
<div class="radio">
<label>
<input id="vendor" type="radio" ng-model="c.data.cvendor" name="customerType" value="cvendor" ng-true-value="CVendor" ng-false-value="false">
${CVendor}
</label>
</div>
Once this option checked, the two fields below should be displayed and are mandatory. How can I achieve this in HTML?
<div class="form-group is-required">
<label for="fieldb">${FieldB}:</label>
<input type="text" class="my-input" ng-model="c.data.fieldb" id="fieldb" placeholder="Enter Field B">
</div>
<div class="form-group is-required">
<label for="fieldc">${FieldC}:</label>
<input type="text" class="my-input" ng-model="c.data.fieldc" id="fieldc" placeholder="Enter Field C">
</div>
Try this ng-if="c.data.cvendor==='cvendor'".
Radio button sets c.data.cvendor to 'cvendor'. Thus you can control the display of two input fields via ng-if
As for the fields to be mandatory, you can try ng-required="true".
<div class="form-group is-required" ng-if="c.data.cvendor==='cvendor'">
<label for="fieldb">${FieldB}:</label>
<input type="text" class="my-input" ng-model="c.data.fieldb" id="fieldb" placeholder="Enter Field B" ng-required="true">
</div>
<div class="form-group is-required" ng-if="c.data.cvendor==='cvendor'">
<label for="fieldc">${FieldC}:</label>
<input type="text" class="my-input" ng-model="c.data.fieldc" id="fieldc" placeholder="Enter Field C" ng-required="true">
</div>
Try This code
var checkBox;
function DemoFunctin() {
checkBox = document.querySelector('input[type="checkbox"]');
var textInput1 = document.querySelector('input[name="first"]');
var textInput2 = document.querySelector('input[name="second"]');
if (textInput1.hasAttribute('required') !== true && textInput2.hasAttribute('required') !== true) {
textInput1.setAttribute('required','required');
textInput2.setAttribute('required','required');
}
else {
textInput1.removeAttribute('required');
textInput2.removeAttribute('required');
}
}
if(checkBox){
checkBox.addEventListener('change',toggleRequired,false);
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<h3>display-two-fields-as-mandatory-based-on-selected-radio-button</h3>
<form>
<p><input type="radio" onclick="DemoFunctin();"/>Check Me to make the Text Box a Required Field</p>
<input type="text" name="first"/>
<input type="text" name="second"/>
<input type="submit" value="Submit" />
</form>
</body>
</html>
You can achieve this by using ng-required. Based on 'c.data.fieldb' value it will become mandatory or non-mandatory. Similarly, for hide and show you can use ng-show / ng-hide.
<div class="form-group is-required">
<label for="fieldb">${FieldB}:</label>
<input type="text" class="my-input" ng-model="c.data.fieldb" id="fieldb" placeholder="Enter Field B" ng-required="c.data.cvendor == 'CVendor'">
</div>
<div class="form-group is-required">
<label for="fieldc">${FieldC}:</label>
<input type="text" class="my-input" ng-model="c.data.fieldc" id="fieldc" placeholder="Enter Field C" ng-required="c.data.cvendor == 'CVendor'">
</div>

target and remove containing parent div tag not the contents

I have a section of code which I don't have full control over which includes a Div with no class or id. I'd like to remove the opening and closing tag of this Div and keep the existing content, but not sure how to target this and remove ?
currently...
<li id="foo" class="underline">
<div>
<input id="username" name="username" required="required" class="validate" type="text">
</div>
<label for="username">Username</label>
</li>
the final result i would like...
<li id="foo" class="underline">
<div class="mynewdiv">
<input id="bar" name="bar" required="required" class="validate" type="text">
<label for="bar">Username</label>
</div>
</li>
I have control to add teh newDiv. My question has similarities to how can I remove wrapper (parent) without removing the child
but i'm not sure how to properly target this unnamed div (with closest?). Thanks
You can use .append() on your div and inside that find the label
$(".underline div").append(function(){
return $(this).next("label");
}).addClass("mynewdiv");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li id="foo" class="underline">
<div>
<input id="username" name="username" required="required" class="validate" type="text">
</div>
<label for="username">Username</label>
</li>

Checkbox to button focus

I've got multiple forms on my page. In one form I've got 3 text fields a check box and a button. When the tab key is pressed, it goes to the 3 text fields and then to the checkbox and then no where.
How can I focus the button (submit) after the checkbox (maths) and then back to the first text field (user_id).
<form id="form13">
User ID :<input type="text" id="user_id" /><br>
Password: <input type="password" id="password" /><br>
Department: <input type="text" id="department" /><br>
<input type="checkbox" id="maths" value="on"> Maths
<input type="submit" id="submit" value="Submit" />
</form>
$('#maths').keydown(function(e){
if (e.which == 9){
$('#submit).focus();
}
});
If your need is to handle Tabbing in your HTML forms. Then you may need to handle this with HTML attribute tabindex this is a good article for learning purpose:
<input id="foo" tabindex="1" />
<input id="bar" tabindex="3" />
<input id="awesome" tabindex="2" />
So, you can handle it in your way. And yes, you can also change it dynamically by using Javascript:
document.getElementById("foo").tabIndex = "3";
I hope it may help you.
You should organize your form in such a way that it can be navigated using the keyboard only.
For example, have a look at this form:
Accessible Signup form
Manually setting the tabindex may lead to problematic behavior. There are couple of good article why you should not do it:
Using the tabindex attribute
Don’t Use Tabindex Greater than 0
Be aware when manually setting a tabindex as suggested, this will affect natural flow of tab index in form and document. Use this only when you are absolutely sure about it.
You can organize your form in such a way that keyboard navigation of your form works without you using tabindex.
Have a look at following Pen : Form field focus, you'll see that from checkbox, the focus goes directly to submit button and back :
<form id="form13">
<label for="asdfg-user_id" id="user_id-ariaLabel">
User ID: <input type="text" id="asdfg-user_id" />
</label>
<br>
<label for="password" id="password-ariaLabel">
Password: <input type="password" id="password" />
</label>
<br>
<label for="password" id="password-ariaLabel">
Department: <input type="text" id="department" />
</label>
<br>
<fieldset id="interestInfo">
<legend>Subject </legend>
<div>
<div id="interests"></div>
<div>
<div class="row">
<input id="chk_Subject_1_lbl" name="chk_Subject[]"
type="checkbox"
value="on"/>
<span>
<label for="chk_Subject_1" id="AreaOfInterest_1-ariaLabel" >Math</label>
</span>
</div>
<div class="row">
<input id="chk_Subject_2_lbl" name="chk_Subject[]"
type="checkbox"
value="on"/>
<span>
<label for="chk_Subject_2" id="AreaOfInterest_2-ariaLabel" >Chemistry</label>
</span>
</div>
</div>
</div>
</fieldset>
<input type="submit" id="submit" value="Submit" />
</form>

Showing input when CheckBox is checked

I am creating a contact form, I have two inputs, of type="checkbox"; the first one is email, and is already checked, but I want to uncheck this, in the event that the user picks the "Phone" option, and show the phone input in which to enter the phone number.
Here's the code:
at JS Fiddle
I hope you guys can help me, I'm still a js newbie but I have learnt a lot.
HTML
Name *:
<label for="">Email <span>*</span>:</label>
<input type="email" placeholder="Email (Required)">
<label for="">Got a question? <span>*</span>:</label>
<textarea name="" id="" rows="1" placeholder="Got a question? (Required)"></textarea>
<label for="">Best form to contact</label>
<div>
<p>Email: </p>
<input type="checkbox" name="fruit" value="email" id="email2" checked>
</div>
<div>
<p>Phone: </p>
<input type="checkbox">
<input type="text" placeholder="Give us your phone" id="phonecheck" class="NoDisplayed">
</div>
<div class="SendButton">
Send
</div>
</form>
</div>
</div>
Javascript
$('#ChatContainer').hide();
$('.NoDisplayed').hide();
$('#ChatToggle').click(function(){
$('#ChatContainer').toggle('slow');
});
Thank you.
I'd suggest associating your 'preferred contact' choices together, using radio-inputs (since 'preferred' is an exclusive choice to make, whereas 'acceptable' might include all possible options), giving:
<label for="">Best form to contact</label>
<div>
<p>Email:</p>
<input type="radio" name="contact" value="email" id="email2" checked="checked" />
</div>
<div>
<p>Phone:</p>
<input type="radio" name="contact" value="phone" />
<input type="text" placeholder="Give us your phone" id="phonecheck" class="NoDisplayed" />
</div>
Which would work with the following jQuery:
$('input[type="radio"][name="contact"]').on('change', function(){
$('#phonecheck').toggle(this.value === 'phone');
});
JS Fiddle demo.
It's worth also noting that your HTML is somewhat problematic; your <label> elements weren't associated with any (let alone 'specific') form-elements; you were using a <label> simply to provide a form's section-name (for which the <legend> attribute should be used, within a <fieldset> grouping). That said, I've corrected your HTML and moved the phone-number entry box outside of the <div> that was containing the checkbox (and now contains a radio-input), to reduce the jarring effect of the <form> suddenly being displaced. There's still a bit of a jump, but not quite so profound.
Here's the amended HTML, which still works with the above jQuery:
<div id="ContactForm">
<div id="ChatToggle">
<p>Contact Us</p>
</div>
<div id="ChatContainer">
<form action="">
<label>Name <span>*</span>:
<input type="text" placeholder="Your Name (Required)" />
</label>
<label>Email <span>*</span>:
<input type="email" placeholder="Email (Required)" />
</label>
<label>Got a question? <span>*</span>:
<textarea name="" id="" rows="1" placeholder="Got a question? (Required)"></textarea>
</label>
<fieldset>
<legend>Best form to contact</legend>
<div>
<label>Email:
<input type="radio" name="contact" value="email" id="email2" checked="checked" />
</label>
</div>
<div>
<label>Phone:
<input type="radio" name="contact" value="phone" />
</label>
</div>
<input type="text" placeholder="Give us your phone" id="phonecheck" class="NoDisplayed" />
</fieldset>
<div class="SendButton"> Send
</div>
</form>
</div>
</div>
JS Fiddle demo.
References:
CSS:
Attribute-equals (attribute="value") selector.
HTML Elements:
<fieldset>.
<label>.
<legend>.
<input />.
jQuery:
on().
toggle().
Try this code:
var $checkPhone = $('#checkPhone');
var $checkMail = $('#checkMail');
var $phonecheck = $('#phonecheck');
$checkPhone.change(function(data) {
$checkMail.attr("checked", false);
if (this.checked) {
$phonecheck.show();
}
else {
$phonecheck.hide();
}
});
$checkMail.change(function(data) {
$checkPhone.attr("checked", false);
$phonecheck.hide();
});
remove the class NoDisplayed form the phone element and repelace it by style="display: none;"
http://jsfiddle.net/dL36kccw/8/
Addition:
Doing such stuff with jQuery is not the easiest. You often end up in placing some DOM manipulations in several places which makes the code less maintainable (like the $phonecheck.hide(); in this case.
I can strongly recommend to take a look into Knockout or some other UI framework. A good list of frameworks + examples can be found on todoMVC. I think Knockout is the best for many cases. Backbone is very competitive, too. But in the end you need to find one that reflects your needs and style.
Edit: Fixed the bug with unchecking the pohne.
You just need to handle the change event of the phone checkbox:
$("#chkPhone").on("change", function () {
$("#email2").prop("checked", !($(this).is(":checked")));
});
http://jsfiddle.net/dL36kccw/5/
// I have just added id (id -->"phone" to checkbox for corresponding phone number text box and added style="display:none;" to phone number text
<label for="">Email <span>*</span>:</label>
<input type="email" placeholder="Email (Required)">
<label for="">Got a question? <span>*</span>:</label>
<textarea name="" id="" rows="1" placeholder="Got a question? (Required)"></textarea>
<label for="">Best form to contact</label>
<div>
<p>Email: </p>
<input type="checkbox" name="fruit" value="email" id="email2" checked>
</div>
<div>
<p>Phone: </p>
<input type="checkbox" id="phone">
<input type="text" placeholder="Give us your phone" id="phonecheck" style="display:none;">
</div>
<div class="SendButton">
Send
</div>
</form>
</div>
</div>
// please try this script
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$('#phone').click(function(){
if($('#phone').is(':checked'))
{
$('#phonecheck').show();
}
else
{
$('#phonecheck').hide();
}
});
</script>

Categories