Need help Selecting - jquery-selectors

I have HTML similar to this :
<div class="MainForm">
<form name="FromName">
<button name="Button1"></button>
...
...
</form>
<Div class="blackBox" style="visibility:hidden;"></div>
<Div class="SubFotm" style="visibility:hidden;"></div>
</div>
Now I can properly find the trigger for my button click in my script, but I'm not able to target only the closet blackbox to turn it visible.
Currently I'm doing :
if (PButtonName=="Fermer") {
$(this).closest("div .ProfileForm").remove(); // Closing Profile Form
} else if (PButtonName=="plusAdresse") {
alert('In');
$(this).closest("div .BlackBox").css("visibility","visible");
}
I can get the alert "In" to show, but not the BlackBox
If I change the
$(this).closest("div .BlackBox").css("visibility","visible");
for :
$("div .FormBlackBox").css("visibility","visible");
It will show, but will also show all the black box in the document.

If you are using the above HTML, or something similar, I would do it using a reference to the parents.
instead of:
$(".MainForm").closest("div .BlackBox").css('visibility','visible');
use
$(this).parents('.MainForm').children('.BlackBox').css('visibility','visible');
This is assuming you have more than one MainForm div and they all have a single child with the BlackBox class.
here is an example.

Instead of what you have done just add styles display:none; to your divs and then show them whenever you want.So you can do this as below:
<div class="MainForm">
<form name="FromName">
<button name="Button1"></button>
...
...
</form>
<div class="blackBox" style="display:none;"></div>
<div class="SubFotm" style="display:none;"></div>
</div>
and then in your script
if (PButtonName=="Fermer")
{
$(".MainForm").closest("div .ProfileForm").remove(); // Closing Profile Form
}
else if (PButtonName=="plusAdresse")
{
alert('In');
$(".MainForm").closest("div .BlackBox").show();
}
And I will recommend you using Switch case instead of loops at this place.

Related

meteor - how to code a bootstrap modal template to re-render html input values even if the user has typed in them

I'm using iron router to pass data to a bootstrap modal template. The modal contains a html form including many text inputs. The modal is re-used for 3 different features. I use a Session variable to keep track of which modal type is in use. Type 0 = blank form, type 1 = partial edit, type 2 = full edit. The form itself remains the same visually for all types. The only thing that changes is which input boxes contain a value.
For a type 1 edit only 2 boxes would contain values. For a type 2 edit all boxes would contain values. And the type 0 would be empty boxes.
// routes.js
Router.route('/mypage', function () {
var mtype = Session.get("mtype");
this.layout('myLayout');
this.render('my_popup', {to:'my_popup', data: function() {
switch (mtype) {
case 1:
return {box1:'box 1 text', box2:'box 2 text', box3:''};
case 2:
return {box1:'box 1 text', box2:'box 2 text', box3:'box 3 value'};
default:
return {box1:'', box2:'', box3:''};
}
}});
});
// main.html
<template name="myLayout">
{{> yield "my_popup"}}
</template>
<template name="my_popup">
<div class="modal fade" id="my_popup">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<div class="modal-title label label-primary">Title</div>
</div>
<div class="modal-body">
<form class="js-form-submit" id="my_form" name="my_form">
<div class="form-group">
<input class="form-control" type="text" name="box1" maxlength="64" placeholder="something" value="{{box1}}"/>
</div>
<div class="form-group">
<input class="form-control" type="text" name="box2" maxlength="64" placeholder="something" value="{{box2}}"/>
</div>
<div class="form-group">
<input class="form-control" type="text" name="box3" maxlength="64" placeholder="something" value="{{box3}}"/>
</div>
</form>
</div>
<div class="modal-footer">
<button class="js-form-ok btn btn-success btn-sm">submit</button>
<button class="btn btn-warning btn-sm" data-dismiss="modal">cancel</button>
</div>
</div>
</div>
</div>
</template>
Initially I tried passing an object to the modal template that only contained the properties that would be displayed. That didn't overwrite existing input values so I had to use the same object for each modal type and use empty strings for unused properties. I tried calling the reset() method on the form prior to showing the modal. In that case it caused the entire template to stop re-rendering.
Prior to showing the modal I set the session variable to the type of modal that will be displayed.
Session.set('mtype', 1);
That triggers iron router into sending the proper data to the template, unused properties are cleared and the template successfully re-renders.
Unfortunately if I type in one of the html inputs the template does not reset its value when it's re-rendered. This seems to be related to the same problem I encountered with the reset() method. If the input contains custom text (value is typed) then the modal doesn't display the new data sent to the template when the Session variable is changed. It preserves the user entered text.
What's the best way to re-use a bootstrap modal form in meteor? Should I use a helper instead of iron router to get the data object? Something like...
{{#with getData}}
Why is the user entered text being preserved?
I've also tried using the defaultValue attribute instead of value. The same issue occurs with both attributes.
To test the bug:
open the web console
Session.set('mtype',1);
$('#my_popup').modal('show');
type something in the 3rd text box
click off the modal to hide it
Session.set('mtype',0);
$('#my_popup').modal('show');
You'll see that the value you typed is still visible despite having sent empty strings to each box.
Another way:
Session.set('mtype',2);
$('#my_form')[0].reset();
Session.set('mtype',1);
$('#my_popup').modal('show');
You'll see that none of the boxes contain values despite having sent new strings of text to each box.
The only solution I've found is to use defaultValue in the template and then loop through the form fields before modal is shown and set value = defaultValue.
<input class="form-control" type="text" name="box1" maxlength="64" placeholder="something" defaultValue="{{box1}}"/>
Template.my_popup.rendered = function() {
$("#my_popup").on('show.bs.modal', function() {
var elems = $('#my_form')[0].elements;
for (var i=0; i<elems.length; i++) {
if (elems[i].hasAttribute('defaultValue')) {
elems[i].value = elems[i].getAttribute('defaultValue');
}
}
});
};

Bootstrap Dropdown Toggle Icon issue

I am using Twitter Bootstraps "dropdown menu" on WordPress for some widget I created and it works fine. But I want to change the icon to "minus" when it drops the content and when another "plus"-icon is clicked the "minus" should close. At the moment it will only toggle the current "plus".
<div class="dropdown toggle-details">
<img src="">
<h3>title</h3>
<h4><subtitle</h4>
<a class="dropdown-toggle my-btn" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true"><i class="fa fa-plus-circle"></i></a>
<ul class="dropdown-menu" >
<li> <h6>item 1</h6></li>
<li><h6>item 2</h6></li>
</ul>
</div>
my script is
jQuery('a').click(function() {
jQuery(this).find('i').toggleClass('fa-minus-circle');
jQuery(this).find('fa-minus-circle').toggleClass('fa-plus-circle')});
You're missing a dot in your jQuery, so right now jQuery is looking for an html element with tag name fa-minus-circle within the "a" element. And obviously not finding it.
jQuery(this).find('.fa-minus-circle').toggleClass('fa-plus-circle')...
actually that probably won't fix it either, because after that statement you'll end up with both classes on the i element. I guess you could work around that with css, but cleaner would be to have the "i" element default to a + icon, and then toggle a more semantic class name like "open".
So css:
i { /* show plus icon */ }
i.open { /* show minus icon */ }
And jQuery:
jQuery("a").on("click", function() {
jQuery(this).find("i").toggleClass("open");
});
Heh - now that I just typed everything out I see what you were doing with that second statement. So yeah, you just need a dot so jquery looks for the classname not the element.

Jquery mobile : popup removed from DOM

In my JQUerymobile pages, I have embedded popup div.
Here is an example of my pages content :
<html>
<head>...</head>
<body>
<div data-role="page" id="myPage" data-dom-cache="true" data-theme="a">
<div data-role="content" data-theme="a" >...</div>
<div data-role="footer" data-theme="a" data-id="footer-sante" data-position="fixed">...</div>
<div data-role="popup" id="popupOne" data-dom-cache="true" data-theme="b">
</div>
</div>
<div data-role="popup" id="popupTwo" data-dom-cache="true" data-theme="b">
...
</div>
</body>
</html>
I navigate from pages to anothers. Suddently, my embedded popups disappear from my DOM when I inspect my code.
As shown in my example, the popup location in the source code doesn't seem to change anything to the problem.
Since popups are removed from DOM, the code bellow does nothing (it actually worked before) :
$('#popupOne').trigger('create');
$('#popupOne').popup({ transition: "slidedown", position:"position-header" });
$('#popupOne').popup('open');
Is there a solution to keep my popups in my DOM ?
Is there a better location to embed popups in source code ?
Another way could be to load a popup from an external (cached) page but i never achieved to do that by javascript.
Any idea to solve the problem (or a workaround) ?
(Both) your HTML placements might be incorrect here. Remove the popupOne markup from the end of the page and paste it inside the div with data-role=content like this :
<div data-role="page" id="myPage" data-dom-cache="true" data-theme="a">
<div data-role="content" data-theme="a" >
<div data-role="popup" id="popupOne" data-dom-cache="true" data-theme="b"></div>
</div>
<div data-role="footer" data-theme="a" data-id="footer-sante" data-position="fixed">...</div>
</div>
And if you want to reuse popups, I suggest you go the JS way. You could create popups n the fly and open them. Here's some code which does just that. Feel free to alter it to any thing you want :)
$.extend({
"makePopup": function (text) {
var $popup;
//creat popup element
$popup = $("<div/>", {
"data-role": "popup",
"data-theme": "a",
"data-overlay-theme": "a",
"data-transition": "pop"
}).popup();
//create close element
var $close = $("<a/>", {
"data-role": "button",
"html": "Close",
"href": "#",
"data-theme": "e"
}).on("click", function () {
//click event of close element
$(this).closest("[data-role=popup]").popup("close");
}).buttonMarkup();
//create content div - makes a nice jQM page structure.
var $content = $("<div/>", {
"data-role": "content",
//change this any way you want- Im just adding the text from clicked link here.
"html": "<span>" + text + "</span>"
});
//append $close to $content, then append $content to $popup
$content.append($close).appendTo($popup);
return $popup;
}
});
And when you want to use this, just do this,
var popupEl = $.makePopup("Some HTML");
And then you could, say, open it :
popupEl.popup("open");
Or simply,
$.makePopup("Some HTML").popup("open");
Here's a demo : http://jsfiddle.net/hungerpain/xjz3V/
Hope this is what you wanted :)

Trigger validation of all fields in Angular Form submit

I'm using this method: http://plnkr.co/edit/A6gvyoXbBd2kfToPmiiA?p=preview to only validate fields on blur. This works fine, but I would also like to validate them (and thus show the errors for those fields if any) when the user clicks the 'submit' button (not a real submit but a data-ng-click call to a function)
Is there some way to trigger validation on all the fields again when clicking that button?
What worked for me was using the $setSubmitted function, which first shows up in the angular docs in version 1.3.20.
In the click event where I wanted to trigger the validation, I did the following:
vm.triggerSubmit = function() {
vm.homeForm.$setSubmitted();
...
}
That was all it took for me. According to the docs it "Sets the form to its submitted state." It's mentioned here.
I know, it's a tad bit too late to answer, but all you need to do is, force all forms dirty. Take a look at the following snippet:
angular.forEach($scope.myForm.$error.required, function(field) {
field.$setDirty();
});
and then you can check if your form is valid using:
if($scope.myForm.$valid) {
//Do something
}
and finally, I guess, you would want to change your route if everything looks good:
$location.path('/somePath');
Edit: form won't register itself on the scope until submit event is trigger. Just use ng-submit directive to call a function, and wrap the above in that function, and it should work.
In case someone comes back to this later... None of the above worked for me. So I dug down into the guts of angular form validation and found the function they call to execute validators on a given field. This property is conveniently called $validate.
If you have a named form myForm, you can programmatically call myForm.my_field.$validate() to execute field validation. For example:
<div ng-form name="myForm">
<input required name="my_field" type="text" ng-blur="myForm.my_field.$validate()">
</div>
Note that calling $validate has implications for your model. From the angular docs for ngModelCtrl.$validate:
Runs each of the registered validators (first synchronous validators and then asynchronous validators). If the validity changes to invalid, the model will be set to undefined, unless ngModelOptions.allowInvalid is true. If the validity changes to valid, it will set the model to the last available valid $modelValue, i.e. either the last parsed value or the last value set from the scope.
So if you're planning on doing something with the invalid model value (like popping a message telling them so), then you need to make sure allowInvalid is set to true for your model.
You can use Angular-Validator to do what you want. It's stupid simple to use.
It will:
Only validate the fields on $dirty or on submit
Prevent the form from being submitted if it is invalid
Show custom error message after the field is $dirty or the form is submitted
See the demo
Example
<form angular-validator
angular-validator-submit="myFunction(myBeautifulForm)"
name="myBeautifulForm">
<!-- form fields here -->
<button type="submit">Submit</button>
</form>
If the field does not pass the validator then the user will not be able to submit the form.
Check out angular-validator use cases and examples for more information.
Disclaimer: I am the author of Angular-Validator
Well, the angular way would be to let it handle validation, - since it does at every model change - and only show the result to the user, when you want.
In this case you decide when to show the errors, you just have to set a flag:
http://plnkr.co/edit/0NNCpQKhbLTYMZaxMQ9l?p=preview
As far as I know there is a issue filed to angular to let us have more advanced form control. Since it is not solved i would use this instead of reinventing all the existing validation methods.
edit: But if you insist on your way, here is your modified fiddle with validation before submit. http://plnkr.co/edit/Xfr7X6JXPhY9lFL3hnOw?p=preview
The controller broadcast an event when the button is clicked, and the directive does the validation magic.
One approach is to force all attributes to be dirty. You can do that in each controller, but it gets very messy. It would be better to have a general solution.
The easiest way I could think of was to use a directive
it will handle the form submit attribute
it iterates through all form fields and marks pristine fields dirty
it checks if the form is valid before calling the submit function
Here is the directive
myModule.directive('submit', function() {
return {
restrict: 'A',
link: function(scope, formElement, attrs) {
var form;
form = scope[attrs.name];
return formElement.bind('submit', function() {
angular.forEach(form, function(field, name) {
if (typeof name === 'string' && !name.match('^[\$]')) {
if (field.$pristine) {
return field.$setViewValue(field.$value);
}
}
});
if (form.$valid) {
return scope.$apply(attrs.submit);
}
});
}
};
});
And update your form html, for example:
<form ng-submit='justDoIt()'>
becomes:
<form name='myForm' novalidate submit='justDoIt()'>
See a full example here: http://plunker.co/edit/QVbisEK2WEbORTAWL7Gu?p=preview
Here is my global function for showing the form error messages.
function show_validation_erros(form_error_object) {
angular.forEach(form_error_object, function (objArrayFields, errorName) {
angular.forEach(objArrayFields, function (objArrayField, key) {
objArrayField.$setDirty();
});
});
};
And in my any controllers,
if ($scope.form_add_sale.$invalid) {
$scope.global.show_validation_erros($scope.form_add_sale.$error);
}
Based on Thilak's answer I was able to come up with this solution...
Since my form fields only show validation messages if a field is invalid, and has been touched by the user I was able to use this code triggered by a button to show my invalid fields:
// Show/trigger any validation errors for this step
angular.forEach(vm.rfiForm.stepTwo.$error, function(error) {
angular.forEach(error, function(field) {
field.$setTouched();
});
});
// Prevent user from going to next step if current step is invalid
if (!vm.rfiForm.stepTwo.$valid) {
isValid = false;
}
<!-- form field -->
<div class="form-group" ng-class="{ 'has-error': rfi.rfiForm.stepTwo.Parent_Suffix__c.$touched && rfi.rfiForm.stepTwo.Parent_Suffix__c.$invalid }">
<!-- field label -->
<label class="control-label">Suffix</label>
<!-- end field label -->
<!-- field input -->
<select name="Parent_Suffix__c" class="form-control"
ng-options="item.value as item.label for item in rfi.contact.Parent_Suffixes"
ng-model="rfi.contact.Parent_Suffix__c" />
<!-- end field input -->
<!-- field help -->
<span class="help-block" ng-messages="rfi.rfiForm.stepTwo.Parent_Suffix__c.$error" ng-show="rfi.rfiForm.stepTwo.Parent_Suffix__c.$touched">
<span ng-message="required">this field is required</span>
</span>
<!-- end field help -->
</div>
<!-- end form field -->
Note: I know this is a hack, but it was useful for Angular 1.2 and earlier that didn't provide a simple mechanism.
The validation kicks in on the change event, so some things like changing the values programmatically won't trigger it. But triggering the change event will trigger the validation. For example, with jQuery:
$('#formField1, #formField2').trigger('change');
I like the this approach in handling validation on button click.
There is no need to invoke anything from controller,
it's all handled with a directive.
on github
You can try this:
// The controller
$scope.submitForm = function(form){
//Force the field validation
angular.forEach(form, function(obj){
if(angular.isObject(obj) && angular.isDefined(obj.$setDirty))
{
obj.$setDirty();
}
})
if (form.$valid){
$scope.myResource.$save(function(data){
//....
});
}
}
<!-- FORM -->
<form name="myForm" role="form" novalidate="novalidate">
<!-- FORM GROUP to field 1 -->
<div class="form-group" ng-class="{ 'has-error' : myForm.field1.$invalid && myForm.field1.$dirty }">
<label for="field1">My field 1</label>
<span class="nullable">
<select name="field1" ng-model="myresource.field1" ng-options="list.id as list.name for list in listofall"
class="form-control input-sm" required>
<option value="">Select One</option>
</select>
</span>
<div ng-if="myForm.field1.$dirty" ng-messages="myForm.field1.$error" ng-messages-include="mymessages"></div>
</div>
<!-- FORM GROUP to field 2 -->
<div class="form-group" ng-class="{ 'has-error' : myForm.field2.$invalid && myForm.field2.$dirty }">
<label class="control-label labelsmall" for="field2">field2</label>
<input name="field2" min="1" placeholder="" ng-model="myresource.field2" type="number"
class="form-control input-sm" required>
<div ng-if="myForm.field2.$dirty" ng-messages="myForm.field2.$error" ng-messages-include="mymessages"></div>
</div>
</form>
<!-- ... -->
<button type="submit" ng-click="submitForm(myForm)">Send</button>
I done something following to make it work.
<form name="form" name="plantRegistrationForm">
<div ng-class="{ 'has-error': (form.$submitted || form.headerName.$touched) && form.headerName.$invalid }">
<div class="col-md-3">
<div class="label-color">HEADER NAME
<span class="red"><strong>*</strong></span></div>
</div>
<div class="col-md-9">
<input type="text" name="headerName" id="headerName"
ng-model="header.headerName"
maxlength="100"
class="form-control" required>
<div ng-show="form.$submitted || form.headerName.$touched">
<span ng-show="form.headerName.$invalid"
class="label-color validation-message">Header Name is required</span>
</div>
</div>
</div>
<button ng-click="addHeader(form, header)"
type="button"
class="btn btn-default pull-right">Add Header
</button>
</form>
In your controller you can do;
addHeader(form, header){
let self = this;
form.$submitted = true;
...
}
You need some css as well;
.label-color {
color: $gray-color;
}
.has-error {
.label-color {
color: rgb(221, 25, 29);
}
.select2-choice.ui-select-match.select2-default {
border-color: #e84e40;
}
}
.validation-message {
font-size: 0.875em;
}
.max-width {
width: 100%;
min-width: 100%;
}
To validate all fields of my form when I want, I do a validation on each field of $$controls like this :
angular.forEach($scope.myform.$$controls, function (field) {
field.$validate();
});

Meteorjs - select DOM of a template from another template

I have the following
<div id="header">
{{> header}}
</div>
<div class="hidden content_box">
{{> content}}
</div>
"content_box" is hidden at the start.
template "header" has a single button.
<template name="header">
<button id="display_content">Click to display content</button>
</template>
template "content" is just a simple div
<template name="content">
It's me, content
</template>
When I click on the button in the header, I want to "show" the content_box.
How do I achieve this? - or better yet, what is the best way to achieve this type of effect where you need to access the DOM of a template from an event of another template?
Template.header.events "click button#display_content": (e) ->
Template.content.show() ?????
I don't know if it is the best way to do it, but in similar situations what I've done before is to use a session parameter to store the show/hide status of the div. In your click event, you then only need to change the value of the session flag. In the template of the div you want to show/hide, you just return the class name.
Example in JS:
Template.header.events({
"click button#display_content": function () {
Session.set('contentShow', true);
}
});
Template.content.className = function (input) {
return Session.equals('contentShow', true) ? '' : 'hidden';
};
Html
<template name="content">
<div class="{{className}} content_box">
It's me, content
</div>
</template>
You'd need to initialise the session flag to false in Meteor.startup() for example Session.set('contentShow', false);. As session is reactive, the div class name will be re-evaluated automatically when you change the session flag.