Showing posts with label twitter-bootstrap. Show all posts
Showing posts with label twitter-bootstrap. Show all posts

Sunday, October 14, 2018

How to find where event handler added?

Leave a Comment

How can I found the trigger codes if there is a button which can do an event but it seems like has no set event handler? For example widget toolbox buttons in bootsrap templates. The buttons have just a class but they are working well.

<a href="javascript:;" class="collapse" data-original-title="" title=""></a> 

Where are the codes of this collapse function?

2 Answers

Answers 1

The actual code to animate the collapse is in this scss collapse transition

.collapse {   &:not(.show) {     display: none;   } }  .collapsing {   position: relative;   height: 0;   overflow: hidden;   @include transition($transition-collapse); } 

...and the actual transition is set here.

There is javascript that toggles the class states between the following states as documented here:

  1. .collapse - Closed state of the "dropdown" component and the query to know what elements to apply collapse toggle logic to.

  2. .collapsing - Interim state between closed and open in which the css transition is applied.

  3. .collapse.show - Open state of the "dropdown"

I assume that javascript logic is here for showing the "dropdown" when the [data-toggle]=collapse element is clicked in open state. Then the logic for hiding the "dropdown" is here. The show/hide logic is only toggling the css classes to correspond to the states above, which then triggers the css transition above.

Notice the toggle of class on the "dropdown" between clicks

tets

Answers 2

As @A. Wolff said, the default action of a button is to submit a form, which will lead you to another web page, specified on that form.

Have a look at the form element described at W3Schools, you can basically reach the same behaviour using the button element.

If you want to inspect what events are attached to your button, you can right click it and see the elements inspector.

On the image, the Google Chrome's element inspector

If there are no events attached then nothing will be shown, also, if this button belongs to a form, the default action is not considered as a Javascript Event.

If you want to remove all listeners maybe you should take a look to this answer

Read More

Saturday, August 18, 2018

Bootstrap dropdown submenu closing upstream submenu

Leave a Comment

I have a two-level dropdown that's working great, but when I add another level, the JS seems to be removing the open class from the previous submenu, which means that the desired third-level menu can't be seen, even though it does get the open class added.

I've tracked it down to this JS:

  $(function() {    $('li.dropdown-submenu').on('click', function(event) {       event.stopPropagation();       if ($(this).hasClass('open')){           $(this).removeClass('open');       } else {           $('li.dropdown-submenu').removeClass('open');           $(this).addClass('open');      }   }); }); 

This is, I think, doing the undesired closing of the previous submenu. The HTML is very similar to this example.

Using an adaptation of the JS from that example, I get the third level, but then any given open submenu doesn't automatically close when clicking another submenu.

$(document).ready(function(){   $('.dropdown-submenu a').on("click", function(e){     $(this).next('ul').toggle();     e.stopPropagation();     e.preventDefault();   }); }); 

Need the best of both here!

3 Answers

Answers 1

I think you almost had it, you just needed to look for the different clicks.

The approach I took below was to handle all a clicks but then check to see if it had a class of test which then followed your code verbatim or else, if it didn't have a class of test it then hides all the submenus and goes to it's default href.

<script> $(document).ready(function(){   $('.dropdown-submenu a').on("click", function(e){     if ($(this).hasClass('test')) {       $(this).next('ul').toggle();       e.stopPropagation();       e.preventDefault();     } else {       $('.dropdown-submenu ul').hide();     }   }); }); </script> 

Your updated working example: https://www.w3schools.com/code/tryit.asp?filename=FUB7ECWP20DA

Answers 2

Maybe this is what are you looking for.

This code to close submenu when clicking another submenu.

Javascript

$(document).ready(function(){     $('.dropdown-submenu a.test').on("click", function(e){      /* This is to hide all dropdown-menu children if the parent(dropdown-submenu) in the element have been clicked */      $(this).next('ul').find('.dropdown-menu').each(function(){         $(this).hide();     });      /* This is to find another dropdown-menu have has been opened and hide its submenu */        var xw = $(this);     $(this).closest(".dropdown-menu").find('.dropdown-submenu a.test').not(xw).each(function(){         if($(this).next("ul").is(":visible")){             $(this).next("ul").hide();         }     });      $(this).next('ul').toggle();     e.stopPropagation();     e.preventDefault();     }); }); 

And JSFiddle example : https://jsfiddle.net/synz/vasho634/

Answers 3

I hope this is what you want. Here is the Solution, Not Full Proof but upto that extent whre you want

$(document).ready(function(){   $('.dropdown-submenu a.test').on("click", function(e){      siblingUl = $(this).parent().siblings("li.dropdown-submenu").children("ul").css("display");     if(siblingUl == "block"){     $(this).parent().siblings("li.dropdown-submenu").children("ul").toggle();     }     $(this).next('ul').toggle();     e.stopPropagation();     e.preventDefault();   }); }); 
Read More

Thursday, August 9, 2018

Combining color hex blending algorithm with standard CMYK colored buttons

Leave a Comment

I am trying to blend any combination of colors using colored buttons which output a specific hex number in combination with a slider bar from bootstrap that allows the user to indicate the percentage of color they want to use.

I couldn't get the slider to properly run and I'm not sure why.

I do need some help combining the pieces of code into a working algorithm that I can use for my art class. The full code can be found here:

https://jsfiddle.net/mw7optL5/289/

//Hex blending algorithm var mix = function(color_1, color_2, weight) {   function d2h(d) { return d.toString(16); }  // convert a decimal value to hex   function h2d(h) { return parseInt(h, 16); } // convert a hex value to decimal     weight = (typeof(weight) !== 'undefined') ? weight : 50; // set the weight to 50%, if that argument is omitted    var color = "#";    for(var i = 0; i <= 5; i += 2) { // loop through each of the 3 hex pairs—red, green, and blue     var v1 = h2d(color_1.substr(i, 2)), // extract the current pairs         v2 = h2d(color_2.substr(i, 2)),          // combine the current pairs from each source color, according to the specified weight         val = d2h(Math.floor(v2 + (v1 - v2) * (weight / 100.0)));       while(val.length < 2) { val = '0' + val; } // prepend a '0' if val results in a single digit      color += val; // concatenate val to our new color string   }    return color; // PROFIT!   };  //buttons  <button class="Yellow" onclick="mix('#ffff00')">Yellow</button>  <button class="Magenta" onclick="mix('#D9017A')">Magenta</button>  <button class="Cyan" onclick="mix('#009FDF')">Cyan</button>  <button class="Black" onclick="mix('#2D2926')">Black</button>  <button class="Orange021" onclick="mix('#FE5000')">Orange</button>  //slider bar <input id="ex1" data-slider-id='ex1Slider' type="text" data-slider-min="0" data-slider-max="20" data-slider-step="1" data-slider-value="14"/>  var slider = new Slider('#ex1', {     formatter: function(value) {         return 'Current value: ' + value;     } }); 

1 Answers

Answers 1

This just solves the mechanics I think you want (run and save the slider value properly), and it could be used as starter point. This doesn't solve the formula of any combination of colors as you want.

  • Create an object based in the buttons with all percentages (0 default) like { Yellow: 0, Magenta: 0, Cyan: 0, Black: 0 }
  • Add an event listener to each button .click (jquery) or .addEventListener (pure js)
  • In the callback of each button, save the color and percentage into the object, like colorPercentages[colors[i].getAttribute("id")] = $("#ex1").val(); where $("#ex1").val() is the slider's value.
  • Draw the color based in some formula, like $("body").css('background-color', 'rgb(' + r + ', ' + g + ', ' + b + ')');

In this case I've used this formula:

Red = 255 x ( 1 - Cyan / 100 ) x ( 1 - Black / 100 )

Green = 255 x ( 1 - Magenta / 100 ) x ( 1 - Black / 100 )

Blue = 255 x ( 1 - Yellow / 100 ) x ( 1 - Black / 100 )

Here a full functional example based on @barbsan modifications: https://jsfiddle.net/5dsgbne9/

That example is using the color button click event, but you could use the inverse logic as well, changing the color when user moves the slider with something like:

$("#ex1").slider().on('slideStop', function(ev){     //code }); 

As I understand, a blending algorithm it's pretty difficult to achieve, this question and the answers give some good approaches: Mixing two colors "naturally" in javascript, but you still need to mix n colors, not just 2, which is even more complex. Fortunately it seems to be not impossible.

Read More

Tuesday, August 7, 2018

Form in view breaking CSS/JS performance optimizations

Leave a Comment

I am struggling with the performance optimizations for scripts and CSS in Asp.Net Core MVC app.

I use bootstrap with LoadCSS to preload it. FontsAwesome CSS and JavaScripts are loaded after the content.

My _Layout page looks something like this.

<head>  <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1">       <script>     LoadCSS script here... </script>  <script async defer src="https://use.fontawesome.com/releases/v5.2.0/js/all.js" integrity="sha384-4oV5EgaV02iISL2ban6c/RmotsABqE4yZxZLcYMAdG7FAPsyHYAPpywE9PJo+Khy" crossorigin="anonymous"></script>  <link rel="preload" as="style" type="text/css" onload="this.onload=null;this.rel='stylesheet'" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous">  <noscript>     <link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous"> </noscript>   <style>     inline critical path CSS here... </style>  </head> <body>  <div class="container-fluid body-content">     @RenderBody()     @RenderSection("scripts", false) </div> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script async src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js" integrity="sha384-o+RDsa0aLu++PJvFqy8fFScvbHFLtbvScb8AjopnFD+iEQ7wo/CG0xlczd+2O/em" crossorigin="anonymous"></script> </body> 

This works great and I am getting good performance scores (94 on Google PageSpped), as long as the page does not contain an input form.

For pages that do have input form, performance optimizations stop working, and Google PageSpeed is complaining about render blocking jquery.js and bootstrap CSS. For some reason Bootstrap seems to load twice!? Below is what the PageSpeed says for the pages with the form, other pages don't have this issue.

Remove render-blocking JavaScript:

https://code.jquery.com/jquery-3.3.1.slim.min.js

Optimize CSS Delivery of the following:

https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css

I don't quite understand what is happening here. Somehow, presence of of the form seems to force bootstrap to load early and preload and LoadCSS does not "work".

The form does use client side data validation, possibly this is the culprit.

1 Answers

Answers 1

I managed to resolve the problems. I read on a number of sites that JavaScript should be placed just before closing body tag for best performance, but it seems this advice is somewhat dated. It actually makes more sense to place scripts in the head and use defer. Defer will load them in parallel without blocking rendering and execute them after and in order, which is perfect.

The CSS problem was due to some missing items in inline critical CSS, namely form-control. This was causing the entire CSS to be loaded, for some reason twice. I used penthouse to generate the critical CSS for each page then merged them.

Improved layout page:

<head>  <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1">       <script>     LoadCSS script here... </script>  <script async defer src="https://use.fontawesome.com/releases/v5.2.0/js/all.js" integrity="sha384-4oV5EgaV02iISL2ban6c/RmotsABqE4yZxZLcYMAdG7FAPsyHYAPpywE9PJo+Khy" crossorigin="anonymous"></script>  <link rel="preload" as="style" type="text/css" onload="this.onload=null;this.rel='stylesheet'" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous">  <noscript>     <link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous"> </noscript>   <style>     inline critical path CSS here... </style>  <script defer src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script defer src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script> <script defer src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>  </head>  <body>  <div class="container-fluid body-content">     @RenderBody()     @RenderSection("scripts", false) </div>  </body> 
Read More

Sunday, August 5, 2018

Place button next to selectInput

Leave a Comment

Goal

I want to place a selectInput and an actionButton side by side in the footer of my shinydashboard::box. The button should be "relatively close" to the selectInput irrespective of the width of the box.

What I have tried so far

So far I tried column, splitLayout or styling via display: inline-block, but I am not happy with either of the solutions:

  • column: depending on the width of the box, the gap between selectInput and actionButton is too big (I could partially solve that by extending the selectInput width to 100%, but then the width is too large)
  • splitDesign: best option so far, but cellWidths needs adaptation based on box width and works also only with 100% selectInput width and for big boxes, the width of the second split seems to be too big
  • inline-block: does not play well with the general CSS

Example

library(shiny) library(purrr) library(shinydashboard)  widths <- c(1, 2,3, 4, 6, 12)  makeBoxes <- function(width, method = c("split", "col", "css")) {    method <- match.arg(method)    split <- function(width, count) {       splitLayout(selectInput(paste("sel", width, count, sep = "_"), NULL, LETTERS,                               width = "100%"),                   actionButton(paste("ab", width, count, sep = "_"), icon("trash")),                   cellWidths = c("87.5%", "12.5%"),                   cellArgs = list(style = "vertical-align: top"))    }    col <- function(width, count) {       fluidRow(column(width = 11,                       selectInput(paste("sel", width, count, sep = "_"), NULL, LETTERS,                                   width = "100%")),                column(width = 1,                       actionButton(paste("ab", width, count, sep = "_"), icon("trash"))))    }     css <- function(width, count) {       fluidRow(div(selectInput(paste("sel", width, count, sep = "_"), NULL, LETTERS),                    style = "display: inline-block; vertical-align: top"),                actionButton(paste("ab", width, count, sep = "_"), icon("trash")))    }     wrap <- function(method, ...)       switch(method, split = split(...), col = col(...), css = css(...))     map(seq(1, 12 / width, 1), function(count)       box(solidHeader = TRUE, title = "Box", status = "info", width = width,           footer = wrap(method, width, count))) }  server <- function(input, output) { }  ui1 <- dashboardPage(dashboardHeader(), dashboardSidebar(),                      dashboardBody(map(widths, ~ fluidRow(makeBoxes(.x, "split"))))) ui2 <- dashboardPage(dashboardHeader(), dashboardSidebar(),                      dashboardBody(map(widths, ~ fluidRow(makeBoxes(.x, "col"))))) ui3 <- dashboardPage(dashboardHeader(), dashboardSidebar(),                      dashboardBody(map(widths, ~ fluidRow(makeBoxes(.x, "css")))))  shinyApp(ui1, server) shinyApp(ui2, server) shinyApp(ui3, server) 

1 Answers

Answers 1

I hope this could can be useful. I change width = 11 to 12 and it seems good to me.

Is that what you want ?

library(shiny) library(purrr) library(shinydashboard)  widths <- c(1, 2,3, 4, 6, 12)  makeBoxes <- function(width, method = c("split", "col", "css")) { method <- match.arg(method) split <- function(width, count) {   splitLayout(selectInput(paste("sel", width, count, sep = "_"), NULL, LETTERS,                           width = "100%"),               actionButton(paste("ab", width, count, sep = "_"), icon("trash")),               cellWidths = c("87.5%", "12.5%"),               cellArgs = list(style = "vertical-align: top")) } col <- function(width, count) {   fluidRow(column(width = 12,  # width = 11 -> 12                   selectInput(paste("sel", width, count, sep = "_"), NULL, LETTERS,                               width = "100%")),            column(width = 1,                   actionButton(paste("ab", width, count, sep = "_"), icon("trash")))) }   css <- function(width, count) {   fluidRow(div(selectInput(paste("sel", width, count, sep = "_"), NULL, LETTERS),                style = "display: inline-block; vertical-align: top"),            actionButton(paste("ab", width, count, sep = "_"), icon("trash"))) }   wrap <- function(method, ...)   switch(method, split = split(...), col = col(...), css = css(...))  map(seq(1, 12 / width, 1), function(count)   box(solidHeader = TRUE, title = "Box", status = "info", width = width,       footer = wrap(method, width, count))) }  server <- function(input, output) { }  ui2 <- dashboardPage(dashboardHeader(), dashboardSidebar(),                  dashboardBody(map(widths, ~ fluidRow(makeBoxes(.x, "col")))))  shinyApp(ui2, server) 
Read More

Wednesday, June 13, 2018

Modelling Dynamic Forms as React Component

Leave a Comment

How to model dynamic forms as a React Component?

For example I want to create a form shown in an image below:

  1. How can I model this as a React component?
  2. How can I add dynamicity to that component? For example, clicking on "+ Add" button creates another empty textbox and puts it right below the other already rendered textboxes (as shown in an image below).

Can someone help me with the code for the Form below?

enter image description here

3 Answers

Answers 1

In tags I see redux so I can suggest redux-form. Here you have an example of dynamic forms with redux-form.

Answers 2

I can help you with a reduced way

      import React , {Component} from 'react'   import { connect }from 'react-redux'    class main extends Component{     render(){       return(         <div>                 <BaselineMath/>                 <Algorithms />             </div>       )     }   } const mapStateToProps = ({}) => {     return{}   }   export default connect (mapStateToProps,{})(main)        class BaselineMath extends Component{         constructor(props){             super(props);             this.state={rows:[1]}         }         _getRows{             return this.state.rows.map((res,key)=>{                 return <input placeholder="etc..."/>             })         }         onClickAdd(){             let rows = this.state.rows             rows.push(1)             this.setState({                 rows             })         }         render(){             return(             <div>                 <Button onClick={this.onClickAdd.bind(this)}>ADD row</Button>                 {this._getRows()}             </div>             )         }     }      export default (BaselineMath)       class Algorithms extends Component{         constructor(props){             super(props);             this.state={rows:[1]}         }         _getRows{             return this.state.rows.map((res,key)=>{                 return <input placeholder="etc..."/>             })         }         onClickAdd(){             let rows = this.state.rows             rows.push(1)             this.setState({                 rows             })         }         render(){             return(             <div>                 <Button onClick={this.onClickAdd.bind(this)}>ADD row</Button>                 {this._getRows()}             </div>             )         }     }      export default (Algorithms) 

you can do the algorithm with anything you want

Answers 3

The difference is in the fact, that beyond the state of form values, we also need to handle the state of form shape/structure.

If you render the inputs by traversing some state object, that is representing the shape of the form, than new input is just a new entry in this state object. You can easily add or remove input fields on the form by managing that state object. E.g. you can write something like this (pseudo react code):

// inputs state of math and algorithms const state = { math: [obj1, obj2], algorithms: [obj1, obj2] } // obj ~= {id, value} // render math inputs const mathMarkup = state.math.map(obj => <input value={obj.value} onChange={...} />) // add handler for math field const addMath = () => setState(prevState => ({ math: [...prevState.math, newObj]})) 

Here is the example of such form - codesandbox. It's not 100% as on your screen, but the idea should be understandable. Since there are some unclear requirements on your form, I implemented only first two sections, so you can grasp the idea. And, there are no styles :shrug:

Also, you can extract renderXyz methods to separate components, and improve state shape to meet your needs.

Read More

Monday, May 21, 2018

Bootstrap form validation not working without console error

Leave a Comment

This is Simple form.

This is JS code:

$(document).ready(function() {   $('#ledgerHolderjHolderFormEdit').bootstrapValidator({     feedbackIcons: {       valid: 'glyphicon glyphicon-ok',       invalid: 'glyphicon glyphicon-remove',       validating: 'glyphicon glyphicon-refresh'     },     fields: {       JH_INIT: {         validators: {           notEmpty: {             message: "'First Name' is required."           },           regexp: {             regexp: /^07[a-zA-Z0-9.,:;!-@#\$%\^\&*\)\(+=_-`~><|].+$/,             message: "'Mobile Number' must only start with '07'."           },           stringLength: {             min: 5,             max: 30,             message: "'First Name' must be more than 2 and less than 255 characters long."           }         }       }     }   }); }); 

There are no errors show in console, and could not find errors. Can anyone help me?

2 Answers

Answers 1

Solution Found

There are no effect in form and js. Issue was, I wrote html form in 'edit function'(append html form using jQuery). And after validation function wrote in another function. That is the reason.

After many efforts, I wrote validation inside that 'edit function'. The issue was solved.

Answers 2

Make sure you've included JQuery correctly

Read More

Tuesday, April 3, 2018

Full width background inside Bootstrap container on Safari

Leave a Comment

I found a post here where the same question was asked before. I implemented the solution suggested there and it works fine with Chrome and Firefox. But when I tested it on Safari and Opera, I ended up with a long horizontal scrollbar. I'm not sure how to fix it since I've already added using overflow-x: hidden to the body. You can see it in action here.

HTML

<div class="container">   <div class="level"></div>   <div class="level purple"></div>   <div class="level"></div> </div> 

CSS

html, body {     overflow-x: hidden; } .container {   width:960px;   margin: 0  auto;   border:1px solid black; } .level {   height:100px;   background: #bada55; }  .purple {   position: relative;   background: #663399; }  .purple:before,  .purple:after {   content: "";   position: absolute;   background: #663399;  /* Match the background */   top: 0;   bottom: 0;   width: 9999px;   /* some huge width */ }  .purple:before {   right: 100%;  } .purple:after {   left: 100%; } 

5 Answers

Answers 1

I checked in the link(www.kampuster.com) you shared and found the problem with your code.

Problem: In file all/themes/bootstrap_kampuster/css/style.css, you have provided width: 9999px; for classes .homeBanner:before, .homeBanner:after and .countUpSection:before, .countUpSection:after which is causing the whole problem and is not the right way to do it.

Suggestion: Below is the approach I would suggest you to go with. Here is a pen to better illustrate the suggestion.

.section-first, .section-third {    background-image: url('http://www.kampuster.com/sites/default/files/bannerlogo_babson.jpeg');    background-attachment: fixed;    background-size: cover;  }  .section-first-inner {    background-color: rgba(83, 192, 183, 0.3);  }  .section-first, .section-second, .section-third {  /*   this is just to add height inplace of content */    height: 600px;    color: #ffffff;    overflow: hidden;  }  .section-first-inner, .section-second-inner, .section-third-inner {    padding: 20px 20px;    font-size: 18px;    height: 100%;  }  .section-second {    color: #000;  }
<link href="http://cdn.jsdelivr.net/bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"/>  <!DOCTYPE html>  <html lang="en">    <head>      <title>HTML</title>    </head>    <body>      <div class="main-container">        <header id="page-header"></header>        <div class="section-first">          <div class="section-first-inner">            <div class="container">              <div class="row">                <div class="col-sm-12">                  Your content for section first goes here                </div>              </div>            </div>          </div>        </div>        <div class="section-second">          <div class="section-second-inner">            <div class="container">              <div class="row">                <div class="col-sm-12">                  Your content for section second goes here                </div>              </div>            </div>          </div>        </div>        <div class="section-third">          <div class="section-third-inner">            <div class="container">              <div class="row">                <div class="col-sm-12">Your content for section third goes here</div>              </div>            </div>          </div>        </div>      </div>    </body>  </html>

Answers 2

Instead of setting width:960px; on the container try setting view width: width: 100vw;

So the container css will be:

.container {   width: 100vw;   margin: 0  auto;   border:1px solid black; } 

Answers 3

just use .container-fluid class.

<div class="container-fluid" style="background-image:url('xample.jpg')">  <div class="row">     <div class="col-sm-12">         <div class="container">             <div class="row">                 <div class="col-sm-12">                      your content here                  </div>             </div>         </div>     </div> </div> 

Answers 4

Full width background inside Bootstrap container!!

If this is what you want (Example Demo)

Then simply use Relative Lengths :

vw Relative to 1% of the width of the viewport*

vh Relative to 1% of the height of the viewport*

I have only replaced 2 values in your code:

  1. .container { width:100vw; }

  2. .purple:after { width: 100vw; /* some huge width */ }

Code:

<!-- Latest compiled and minified CSS -->  <  link rel = "stylesheet"  href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >      <!-- jQuery library -->    <    script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" > < /script>      <!-- Latest compiled JavaScript -->    <    script src = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" > < /script>
html,  body {    overflow-x: hidden;  }    .container {    width: 100vw;    margin: 0 auto;    border: 1px solid black;  }    .level {    height: 100vh;    background: #bada55;  }    .purple {    position: relative;    background: #663399;  }    .purple:before,  .purple:after {    content: "";    position: absolute;    background: #663399;    /* Match the background */    top: 0;    bottom: 0;    width: 100vw;    /* some huge width */  }    .purple:before {    right: 100%;  }    .purple:after {    left: 100%;  }
<div class="container">    <div class="level"></div>    <div class="level purple"></div>    <div class="level"></div>  </div>

Answers 5

Please try this, this is working for me.

add the below css, if doesn't work try adding important to them. And to get full width of container, add container-fluid class to particular container.

html, body {     width: -webkit-fill-available;     overflow-x: hidden; } 
Read More

Monday, February 12, 2018

Form validation on click Next Button using bootstrap nav-pill

Leave a Comment

I am using nav-pill inside which there is a form and that is split up into each part say as admission details, personal details, family Details with "Next" button on each step and save button at last nav-pill.

$('.btnNext').click(function() {    $('.nav-pills > .active').next('li').find('a').trigger('click');  });    $('.btnPrevious').click(function() {    $('.nav-pills > .active').prev('li').find('a').trigger('click');  });    //  Bind the event handler to the "submit" JavaScript event  $('#validateFirst').click(function() {      // Get the Login Name value and trim it    var name = $.trim($('#admission_no').val());      // Check if empty or not    if (name === '') {      alert('Admission No. field is empty.');      return false;    }  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>    <ul class="nav nav-pills nav_content">    <li class="active"><a data-toggle="pill" href="#admission">Admission Details</a></li>    <li><a data-toggle="pill" href="#personal">Personal Details</a></li>    <li><a data-toggle="pill" href="#family">Family Details</a></li>  </ul>    <form id="form1" action="<?php echo site_url('student/create') ?>" id="employeeform" name="employeeform" method="post" accept-charset="utf-8" enctype="multipart/form-data">    <div class="tab-content">      <div id="admission" class="tab-pane fade in active">        <div class="row">          <div class="col-md-3">            <div class="form-group">              <label for="exampleInputEmail1">Admission Number *</label>              <input id="admission_no" name="admission_no" placeholder="" type="text" class="form-control" value="admission_no" />            </div>          </div>          <div class="col-md-3">            <div class="form-group">              <label for="exampleInputEmail1">Application Number  *</label>              <input id="application_no" name="application_no" placeholder="" type="text" class="form-control" value="application_no" />            </div>          </div>          <div class="col-md-3">            <div class="form-group">              <label for="exampleInputEmail1">Academic Year  *</label>              <input id="academic_year" name="academic_year" placeholder="" type="text" class="form-control" value="academic_year" />            </div>          </div>        </div>        <a class="btn btn-primary btnNext pull-right" id="validateFirst">Next</a>      </div>      <div id="personal" class="tab-pane fade">        <div class="row">          <div class="col-md-3">            <div class="form-group">              <label for="exampleInputEmail1">First Name *</label>              <input id="firstname" name="firstname" placeholder="" type="text" class="form-control" value="firstname" />            </div>          </div>          <div class="col-md-3">            <div class="form-group">              <label for="exampleInputEmail1">DOB *</label>              <input id="dob" name="dob" placeholder="" type="text" class="form-control" value="DOB" readonly="readonly" />            </div>          </div>          <div class="col-md-3">            <div class="form-group">              <label for="exampleInputFile">Address  *</label>              <textarea id="student_address" name="student_address" placeholder="" class="form-control" rows="2"></textarea>            </div>          </div>        </div>        <a class="btn btn-primary btnPrevious pull-left">Previous</a>        <a class="btn btn-primary btnNext pull-right">Next</a>      </div>      <div id="family" class="tab-pane fade">        <div class="row">          <div class="col-md-3">            <div class="form-group">              <label for="exampleInputEmail1">Father Name *</label>              <input id="father_name" name="father_name" placeholder="" type="text" class="form-control" value="father_name" />            </div>          </div>          <div class="col-md-3">            <div class="form-group">              <label for="exampleInputEmail1">Father Occupation *</label>              <input id="father_occupation" name="father_occupation" placeholder="" type="text" class="form-control" value="father_occupation" />            </div>          </div>          <div class="col-md-3">            <div class="form-group">              <label for="exampleInputEmail1">Mother Name *</label>              <input id="mother_name" name="mother_name" placeholder="" type="text" class="form-control" value="mother_name" />            </div>          </div>        </div>        <a class="btn btn-primary btnPrevious pull-left">Previous</a>        <button type="submit" class="btn btn-info pull-right">Save</button>      </div>    </div>  </form>

I have tried with button click function while clicking "Next" button like:

$('#validateFirst').click(function () {     // Get the Login Name value and trim it     var name = $.trim($('#admission_no').val());     // Check if empty of not     if (name === '') {         alert('Text-field is empty.');         return false;     } }); 

Where button has id "validateFirst",

<a class="btn btn-primary btnNext pull-right" id="validateFirst">Next</a> 

Here it shows alert when the admission no input is not filled but moves to the next tab (i.e.) personal details while clicking the next button. The thing i am in the need is while clicking the next button if the fields in the current nav-pill fields are empty (say admission no field is not filled in first nav pill) and clicking the next button, it should display alert and should not move to next nav-pill to rectify the invalid input fields in the current nav-pill.. I had a look around other questions but I couldn't get a clear solution. Kindly help me with a solution to resolve this issue.

4 Answers

Answers 1

You can do it like this:

$('.pull-right').click(function () {     var validationMessage = '';      // Check inputs are filled.     $.each($(this).closest('.tab-pane').find('input[type="text"]'), function () {         if ($(this).val() == '')              validationMessage += "Please fill " + $(this).closest('.form-group').find('label').html().replace('*', '') + "\n";                });      // Validation is false     if (validationMessage != '')         alert(validationMessage);     else         $('.nav-pills > .active').next('li').find('a').trigger('click'); }); 

Online demo (jsFiddle)

Answers 2

You are already having an event handler on the '.btn-next' Defining an another event handler on the same element will just execute both of them in the order you have attached the event handler.(You can change the order by manipulating the bubbling phase and capturing phase, but that will work only if you are using the addEventListener.)

Solution 1:

You can set a boolean variable and assign the validation status to that and check the status before firing the click event on the next nav-pill.

In this approach the order in which you are binding the event handlers matter.

  var validationStatus = true;      //  Bind the event handler to the "submit" JavaScript event   $('#validateFirst').click(function () {      // Get the Login Name value and trim it     var name = $.trim($('#admission_no').val());      // Check if empty or not     if (name === '') {         alert('Admission No. field is empty.');         validationStatus = false;     }   });    $('.btnNext').click(function(){         if(validationStatus) {         $('.nav-pills > .active').next('li').find('a').trigger('click');     }    });    $('.btnPrevious').click(function(){     if(validationStatus) {             $('.nav-pills > .active').prev('li').find('a').trigger('click');     }   }); 

https://jsfiddle.net/790dejct/

Note: this solution is not scalable and maintainable and its too naive.

Solution 2:

Alternate solution is You need to make sure to validate everything in a single function read the status and fire the nav pill event.

https://jsfiddle.net/8b7pq08a/

  function checkEmpty(selector) {        var isFailed = false;     var name = $.trim($(selector).val());         // Check if empty or not     if (name === '') {         alert(selector + ' field is empty.');         isFailed = true;     }     return isFailed;   }     function validate() {          var isFailed = false;          var listOfRequiredFields = ['#admission_no', '#application_no', '#firstname', '#father_name']; //example it should contain all, ideally you can add a class for all the required elements  and then use it or query all input type elements. This is just for illustration     isFailed =  listOfRequiredFields.some(function(selector, index){             if($(selector).closest('.tab-pane ').hasClass('active')) {                 return checkEmpty(selector)         }                });      return isFailed;       }     $('.nav-pills a').on('hide.bs.tab', function(e) {         if(validate()){ //if failed prevent the default event                 e.preventDefault();         }    });     $('.btnNext').click(function(){     if(!validate()){ //if success then load the next tab          $('.nav-pills > .active').next('li').find('a').trigger('click');     }    });    $('.btnPrevious').click(function(){     if(!validate()) { //if success then load the next tab           $('.nav-pills > .active').prev('li').find('a').trigger('click');     }     }); 

Note: If you want to add multiple validations like checkEmpty you need to make some modifications for "listOfRequiredFields". Converting it to an object with validations functions as value will help you in identifying the functions that has to be executed on the field.

Answers 3

Form validation should involve more than just checking if a field is filled out or not. For this reason you should use Ajax to submit the relevant data to the server, and use server side form validation.

At the top of your page add a hidden div to display validation errors:

<div class="alert alert-danger col-xs-12 hidden" id="error"></div> 

Add a shared "validate" class to all buttons that will trigger your form validation. We will have three distinct sets of validation logic. Give the field an id that matches the function name (for example "validate_1", "validate_2", etc).

<a class="btn btn-primary btnNext pull-right validate" id="validate_1">Next</a> <a class="btn btn-primary btnNext pull-right validate" id="validate_2">Next</a> 

Update your jQuery to include the Ajax POST function. This function submits data to the server where you can use Codeigniter's native form validation:

$('.btnPrevious').click(function() {   $('.nav-pills > .active').prev('li').find('a').trigger('click'); });   $(document).on('click','.validate',function(e){     e.preventDefault();     if($('#error').is(":visible")){         $('#error').empty().addClass('hidden'); //refresh error message if it was triggered previously     }     var form = $(this).closest('form');     $.ajax({                 url: this.id,         type: 'POST',         data: form.serialize(),         dataType: 'html',         success: function(data) {             var result = $.parseJSON(data);             if(result["error"]===undefined){                 $('.nav-pills > .active').next('li').find('a').trigger('click');             }else{                 $('#error').append(result["error"]).removeClass('hidden');             }         },         error: function() { }     }); }); 

And then in your controller:

function validate_1(){ //function name matches element id     $this->load->library('form_validation');         $this->form_validation->set_rules('admission_no', 'Admission Number', 'required|integer|greater_than[0]');     $this->form_validation->set_rules('application_no', 'Application Number', 'required|integer|greater_than[0]');     $this->form_validation->set_rules('academic_year', 'Academic Year', 'required|integer|greater_than[0]');     if($this->form_validation->run() == TRUE){          echo json_encode(array('success' => 1));     }else{         echo json_encode(array('error' =>  validation_errors()));     } }  function validate_2(){     $this->load->library('form_validation');         $this->form_validation->set_rules('firstname', 'First Name', 'required');     $this->form_validation->set_rules('dob', 'Date of Birth', 'required');     $this->form_validation->set_rules('student_address', 'Address', 'required');     if($this->form_validation->run() == TRUE){         echo json_encode(array('success' => 1));     }else{         echo json_encode(array('error' =>  validation_errors()));     } } 

This will allow you to verify that the data has been submitted and that it is valid. The user will still be able to click on their own to navigate from one nav pill to another, but they will not be able to submit the form without filling out the necessary fields.

enter image description here

Answers 4

you see the example here for the demo

https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_form_steps

Read More

Friday, February 2, 2018

Rails bootstrap erb collection_check_boxes not selecting?

Leave a Comment

I have the model Game that represents games. Each game can have related games, so I have another model Related Games so Game.related_games holds the related games for that game.

The related_games model structure is [game_id, name] where game_id is the game's id the relation is linked to, and name is the name of the game that is related to that game.

Now when I display the erb like this:

f.collection_check_boxes :related_games, Game.all, :id, :name 

The related games will not be selected, like its empty, while the game has related games.

Why does it happen?

4 Answers

Answers 1

I think your models are incorrect (or I did not understand your use case). Your RelatedGame model has a game_id and a name. What does this name represent? If this name is the one for the game_id, it is unnecessary (you have the name through the link game_id). If it is the name of another game, you really should have another game_id.

I believe your models should be:

Model Similarity (or another name, this is your RelatedGame, with some changes)

class Similarity < ApplicationRecord   belongs_to :game1, :foreign_key => 'game1_id', :class_name => "Game"   belongs_to :game2, :foreign_key => 'game2_id', :class_name => "Game" end 

Model Game

class Game < ApplicationRecord   has_many :similarities1, :class_name => "Similarity", :foreign_key => "game1_id"   has_many :similarities2, :class_name => "Similarity", :foreign_key => "game2_id"    has_many :similar_games, :through => :similarities1, source: "Game"   has_many :inverse_similar_games, :through => :similarities2, source: "Game"    def all_similar_games     (similar_games + inverse_similar_games).uniq   end end 

Games Controller

def edit   # The game to edit   @game = Game.find_by(id: params[:id])    # The relation table (similarity) where this game is the game1   @related = @game.similarities1    # The games related to this game (all games linked by game2 in the similarities relation, where this game is game1)   @similar_games = @game.similar_games    # All games related to this one through similarity, whether through game1 or game2   @all_similar_games = @game.all_similar_games end 

In the view:

<h1>@game.name</h1> <% form_for @game do |f| %>   <%= f.input_field :name %>   <%= f.collection_check_boxes :similar_game_ids, Game.all, :id, :name) %> <% end %> 

Answers 2

You should use :related_game_ids instead of :related_games.

f.collection_check_boxes :related_game_ids, Game.all, :id, :name

Don't forget to permit :related_game_ids in your controller.

Answers 3

I don't know what is your model look like if your relations ok and model formatted properly then

Try the following

<%= f.collection_check_boxes :game_ids, Game.all, :id, :name do |cb| %>     <% cb.label(class: "checkbox-inline input_checkbox") {cb.check_box(class: "checkbox") + cb.text } %> <% end %> 

and the controller strong parameters use like below

game_ids: [] 

Hope it helps

Answers 4

Did you put in your controller that related_games accepts a hash of ids?

game_controller.rb

private def game_params       params.require(:game).permit(           //fields_of_game,                          related_game_ids: []         )     end 

in you form

games/_form.html.erb

 <%= hidden_field_tag "game[related_game_ids][]", nil %>         <% Related_Games.all.each do |r_games| %>                <%= check_box_tag "game[related_game_ids][]", r_games.id, @game.related_game_id.include?(r_game.id), id: dom_id(r_game) %>               <%= label_tag dom_id(r_game), r_game.name %> <br>          <% end %> 

in your model game.rb did you put the association? Something like this:

accepts_nested_attributes_for :related_games def related_games_attributes=(related_game_attributes)     related_game_attributes.values.each do |related_game_attribute|       related_game = Related_Games.find_or_create_by(related_game)       self.related_game << related_game      end   end 
Read More

Sunday, January 7, 2018

Initialising a dynamically-created btn-group of radio buttons

Leave a Comment

I am busy writing some helper functions for my fellow developers in-office who isn't too familiar with Bootstrap - which takes basic html and creates bootstrap layouts for them.

In this case, I am trying to make a justified horizontal list of radio buttons.

A example is:

    <fieldset data-type="horizontal" data-bootstrap="radiogroup">         <label>             <input type="radio" name="g1" value="default" data-bind="checked: true"/>Recent         </label>         <label>             <input type="radio" name="g1" value="order" data-bind="checked: false"/>By Number         </label>         <label>             <input type="radio" name="g1" value="advanced" data-bind="checked: false"/>Advanced         </label>     </fieldset> 

I execute some JQuery inside the typescript file linked to this page - and the code reads:

    function layoutUnwrappedBootstrapControls() {         $("*[data-bootstrap='radiogroup']")             .each((index, element) => {                 var listOfRadioButtons = $(element).find('label').clone();                 $(element).children().remove();                 $(element)                     .append("<div class='btn-group col-lg-12 col-md-12 col-sm-12 col-xs-12 clearfix' data-toggle='buttons'></div>");                 $(element)                     .children(":first")                     .append(listOfRadioButtons)                     .find("label")                     .addClass("btn btn-primary")                     .css("width", (100 / listOfRadioButtons.length) + '%');                 $(element).children(":first").button().button('refresh'); //< the issue                });     } 

Which produces:

<div class="btn-group col-lg-12 col-md-12 col-sm-12 col-xs-12 clearfix" data-toggle="buttons">     <label class="btn btn-primary" style="width: 33.3333%;">         <input type="radio" name="g1" value="default" data-bind="checked: true" data-mini="true" data-theme="h" id="tz15" checked="checked">Recent     </label>     <label class="btn btn-primary" style="width: 33.3333%;">         <input type="radio" name="g1" value="order" data-bind="checked: false" data-mini="true" data-theme="h" id="tz16">By Number     </label>     <label class="btn btn-primary" style="width: 33.3333%;">         <input type="radio" name="g1" value="advanced" data-bind="checked: false" data-mini="true" data-theme="h" id="tz17">Advanced     </label> </div> 

On the page, this seems fine. The issue I have however, is the data-toggle='buttons' part - it tells me that bootstrap runs some code in order to initialise the list of radio buttons - and it doesn't seem to play nice with dynamically created button-groups.

My attempt to reinitialise the button group doesn't work. Radio Buttons still remain static - doesn't swap out 'active' on the label, and 'checked' on the input.

The spoopier part is: I cannot reproduce my issue on JSFiddle using identical code! it works as expected on JSFiddle: JSFiddle

How can I force a re-initialisation of a dynamically-created button-group?

4 Answers

Answers 1

The issue was the fact that, as @knetsi mentioned in the comments under the question has mentioned, when you do not have bootstrap.js loaded on your site, you will not get an error in the console to point you what the issue was. When, like on my site, you work with both JQuery UI / JQuery Mobile /JQuery and Bootstrap JS, Bootstrap needs to be loaded last - as it will cause a conflict with the other libraries when you attempt to refresh a button

Answers 2

If your code executes after bootstrap has already done it's business, it will not work...

You need to make your code execute before bootstrap...

So you need to either,

  1. Add your scripts before bootstrap if you are using document ready event.
  2. Move your scripts right after your html (in footer) without using document ready event.

Answers 3

If you call document ready again then previous events associated using bootstrap.js will be unbind, which is not a good idea so you can either change the sequence of execution of your script (means before bootstrap.js) or hold document ready event itself until you are done with your script. You can get reference of jquery.holdready here https://api.jquery.com/jquery.holdready/

Answers 4

The following worked for me (locally and in a fiddle).

In addition to incorporating document.ready in a script tag inside the body (mentioned by previous answers) it looks like your knockout binding has a problem. I changed checked: true / checked: false to checked: statusMsg and added statusMsg: ko.observable("default"). Knockout will check a radio box when the observables value is equal to some radio inputs nodeValue. From the documentation:

For radio buttons, KO will set the element to be checked if and only if the parameter value equals the radio button node’s value attribute or the value specified by the checkedValue parameter.

Knockout checked binding documentation

I logged the checked values of the boxes after clicking and it worked.

My code and fiddle below:

<body> <fieldset data-type="horizontal" data-bootstrap="radiogroup">   <label>     <input type="radio" name="g1" value="default" data-bind="checked: statusMsg"/>Recent   </label>   <label>     <input type="radio" name="g1" value="order" data-bind="checked: statusMsg"/>By Number   </label>   <label>     <input type="radio" name="g1" value="advanced" data-bind="checked: statusMsg"/>Advanced   </label> </fieldset> <script> $(document).ready(function() {     $("*[data-bootstrap='radiogroup']")         .each((index, element) => {             var listOfRadioButtons = $(element).find('label').clone();             $(element).children().remove();             $(element)                 .append("<div class='btn-group col-lg-12 col-md-12 col-sm-12 col-xs-12 clearfix' data-toggle='buttons'></div>");             $(element)                 .children(":first")                 .append(listOfRadioButtons)                 .find("label")                 .addClass("btn btn-primary")                 .css("width", (100 / listOfRadioButtons.length) + '%');         });     var viewModel = {         statusMsg: ko.observable("default")     }     ko.applyBindings(viewModel); }); </script> </body> 

Working fiddle here

Read More

Saturday, December 30, 2017

Twitter Boostrap - Align label horizontally to dropdown

Leave a Comment

I would like to have the label for the dropdown next to the dropdown menus.

Find below how my current example looks like:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">  <ul class="nav nav-pills" role="tablist">    <li role="presentation">Order: </li>    <li role="presentation" class="dropdown">      <a href="#" class="dropdown-toggle" id="drop4" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Ticker<span class="caret"></span></a>      <ul class="dropdown-menu" id="menu1" aria-labelledby="drop4">        <li>          <a href="#">Action</a>        </li>        <li>          <a href="#">Another action</a>        </li>        <li>          <a href="#">Something else here</a>        </li>        <li role="separator" class="divider"></li>        <li>          <a href="#">Separated link</a>        </li>      </ul>    </li>  </ul>

Any suggestions how to align the label with the dropdown properly?

Thx in advance!

5 Answers

Answers 1

I'm not sure I understand correctly, but for alignment I would use a flexbox.

.nav-pills {    display: flex;    align-items: center;  }
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />  <ul class="nav nav-pills" role="tablist">    <li role="presentation">Order: </li>    <li role="presentation" class="dropdown">      <a href="#" class="dropdown-toggle" id="drop4" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">                              Ticker                                  <span class="caret"></span>                              </a>      <ul class="dropdown-menu" id="menu1" aria-labelledby="drop4">        <li>          <a href="#">Action</a>        </li>        <li>          <a href="#">Another action</a>        </li>        <li>          <a href="#">Something else here</a>        </li>        <li role="separator" class="divider"></li>        <li>          <a href="#">Separated link</a>        </li>      </ul>    </li>

Answers 2

Just add the below css in your custom css file

.nav-pills>li:not(.dropdown) {     padding: 10px 12px; } 

.nav-pills>li:not(.dropdown) {    padding: 10px 12px;  }
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">  <ul class="nav nav-pills" role="tablist">    <li role="presentation">Order: </li>    <li role="presentation" class="dropdown">      <a href="#" class="dropdown-toggle" id="drop4" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Ticker<span class="caret"></span></a>      <ul class="dropdown-menu" id="menu1" aria-labelledby="drop4">        <li>          <a href="#">Action</a>        </li>        <li>          <a href="#">Another action</a>        </li>        <li>          <a href="#">Something else here</a>        </li>        <li role="separator" class="divider"></li>        <li>          <a href="#">Separated link</a>        </li>      </ul>    </li>

Answers 3

You can simply add padding like this :

/* Optional theme */    @import url('//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css');    ul.nav > li:first-child {   padding:10px 5px;  }
<ul class="nav nav-pills" role="tablist">    <li role="presentation" >Order: </li>    <li role="presentation" class="dropdown">      <a href="#" class="dropdown-toggle" id="drop4" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">                              Ticker                                  <span class="caret"></span>                              </a>      <ul class="dropdown-menu" id="menu1" aria-labelledby="drop4">        <li>          <a href="#">Action</a>        </li>        <li>          <a href="#">Another action</a>        </li>        <li>          <a href="#">Something else here</a>        </li>        <li role="separator" class="divider"></li>        <li>          <a href="#">Separated link</a>        </li>      </ul>    </li>

Answers 4

Use Flex to nav pills

.nav-pills{ display:flex; align-items:center; } 

JS FIDDLE: https://jsfiddle.net/pradeep0594/qfwngj5x/1/ for your reference

Answers 5

I like Gerard's display: flex solution better, but just in case anyone prefers to maintain the original display property, here is an example using only line-height to vertically center both .nav-pills.

<style>      .nav-pills > li {          line-height: 40px;      }      .nav.nav-pills > li > a {          /* removes top & bottom padding */          padding: 0 15px;      }  </style>    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">  <ul class="nav nav-pills" role="tablist">    <li role="presentation">Order: </li>    <li role="presentation" class="dropdown">      <a href="#" class="dropdown-toggle" id="drop4" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Ticker<span class="caret"></span></a>      <ul class="dropdown-menu" id="menu1" aria-labelledby="drop4">        <li>          <a href="#">Action</a>        </li>        <li>          <a href="#">Another action</a>        </li>        <li>          <a href="#">Something else here</a>        </li>        <li role="separator" class="divider"></li>        <li>          <a href="#">Separated link</a>        </li>      </ul>    </li>  </ul>

Read More

Tuesday, November 7, 2017

Setting a component state outside of the component results in error

Leave a Comment

Building a modal component that opens up a bootstrap modal from any part of the app then sets custom states for that component outside of it. It works fine but i always just get this error once i open the modal and I cant seem to figure out why:

Warning: setState(...): Cannot update during an existing state transition (such as within render or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to componentWillMount.` Doesnt really break anything but error keeps showing up.

My code:

layout.js

import React from "react"; import {Link} from 'react-router'; import NotificationSystem from 'react-notification-system';  import AppHeader from "#/ui/header/AppHeader"; import AppFooter from "#/ui/footer/AppFooter";  import Modal from "#/ui/modals/modal/Modal";  import "@/main.scss"; import './layout.scss';   export default class Layout extends React.Component {     constructor(props) {         super(props);     }      componentDidMount() {         app.notify.clear = this.refs.notificationSystem.clearNotifications;         app.notify = this.refs.notificationSystem.addNotification;         app.modal = this.refs.modal.updateProps;     }      render() {         return (             <div class="app">                 <div class="header">                     <AppHeader page={this.props.location.pathname.replace('/', '')}/>                 </div>                 <div class="body">                     {this.props.children}                 </div>                 <div class="footer">                     <AppFooter />                 </div>                  <NotificationSystem ref="notificationSystem" style={false} />                 <Modal ref="modal" />             </div>          );     }; } 

Modal.js

import React from "react"; import ReactDOM from 'react-dom';  import SVGInline from "react-svg-inline"; import {closeSvg} from '#/utils/Svg';  export default class Modal extends React.Component {     constructor(props) {         super(props);          this.state = {             showHeader: true,             showFooter: false,             title: "",             size: '',             className: '',             id: '',             footerContent: null,             showSubmitBtn: true,             showCancelBtn: true,             cancelBtnText: "Cancel",             successBtnText: "Save Changes",             onModalClose: () => {},             showModal: false,             html: () => {}         }          this.updateProps = this.updateProps.bind(this);         this.hideModal = this.hideModal.bind(this);     }      componentWillMount() {         var self = this;          var $modal = $(ReactDOM.findDOMNode(this));     }      componentDidUpdate(prevProps, prevState) {         if(this.state.showModal) {             $('body').addClass('modal-open');         } else {             $('body').removeClass('modal-open');         }     }      componentWillUnmount() {         // $('body').removeClass("modal-open");     }      componentWillReceiveProps(nextProps) {         console.log(nextProps);     }      updateProps(args) {         let merged = {...this.state, ...args};         this.setState(merged);     }      hideModal() {         this.setState({             showModal: false         });          this.state.onModalClose();     }      buildFooter() {         if(this.props.footerContent) {             return (                 <div class="content">                     {this.props.footerContent}                 </div>             )         } else if(this.props.showCancelBtn && this.props.showSubmitBtn) {             return (                 <div class="buttons">                     <button type="button" class="btn btn-default" data-dismiss="modal" onClick={this.props.onModalClose}>{this.props.cancelBtnText}</button>                     <button type="button" class="btn btn-success">{this.props.successBtnText}</button>                 </div>             );         } else if(this.props.showCancelBtn) {             return (<button type="button" class="btn btn-default" data-dismiss="modal" onClick={this.props.onModalClose}>Close</button>);         } else if(this.props.showSubmitBtn) {             return (<button type="button" class="btn btn-success">Save changes</button>);         }     }      render() {         let {             id,             className,             onModalClose,             size,             showHeader,             title,             children,             showFooter,             showModal,             html         } = this.state;          return (             <div class={`modal-wrapper`} >                 {                     showModal ?                         <div class={`modal fade in ${className}`} role="dialog">                             <div class="bg" ></div>                             <div class={`modal-dialog ${size}`}>                                 <div class="modal-content">                                      { showHeader ?                                         <div class="modal-header">                                             <button type="button" class="close" data-dismiss="modal">                                                 <SVGInline svg={closeSvg} />                                             </button>                                             <h4 class="modal-title">{ title }</h4>                                         </div> : '' }                                       <div class="modal-body" >                                         {html()}                                     </div>                                      {  showFooter ?                                         <div class="modal-footer">                                             { this.buildFooter() }                                         </div> : ''                                     }                                  </div>                             </div>                         </div>                     : ''                 }             </div>         );     } } 

SelectDefaultImage.js

import React from "react"; import sass from "./selectdefaultimage.scss"; import FullScreenImageModal from "#/ui/modals/fullscreenimagemodal/FullScreenImageModal";  export default class SelectDefaultImage extends React.Component {     constructor() {         super();          this.state = {             showModal: false,             imgUrl: false,         }     }      showImageModal(image) {         this.setState({             showModal: true,             imgUrl: image         });     }      hideImageModal() {         this.setState({             showModal: false,             imgUrl: false         })     }      onSelectImageClick(e, image) {         $('.select-image-widget .active').removeClass('active');         $(e.target).parent().addClass('active');          // this.props.selectedImage(image)     }      render() {         let {listingManager, images, selectedImage} = this.props;         let {imgUrl} = this.state;          return (             <div class="content">                 <div class="row">                     <div class="col-sm-12">                         <label class="control-label" for="description">Select an Image</label>                     </div>                 </div>                  <div class="row">                     <div class="col-sm-12">                         <div class="select-image-widget">                             {                                 images.map((image, idx) => {                                     return (                                         <div class="selecter" key={idx}>                                             <div class="img" style={{backgroundImage: `url(${listingManager.LISTINGS_PATH + image})` }} onClick={(e) => { this.onSelectImageClick(e, image) }}></div>                                             <i class="fa fa-search-plus" aria-hidden="true" onClick={()=> {this.showImageModal(image)}}></i>                                         </div>                                     )                                 })                             }                         </div>                     </div>                 </div>                 {                     this.state.showModal ?                         app.modal({                             showModal: true,                             className: "fullscreen-image-modal",                             size: "modal-lg",                             html: () => {                                 return (<img src={listingManager.LISTINGS_PATH + imgUrl} />);                             }                         })                     : ''                 }             </div>         )     } } 

1 Answers

Answers 1

The reason for the error is most likely that in SelectDefaultImage, you call app.modal from within the render method, and app.modal is this.refs.modal.updateProps, which does a setState. If you put the app.modal call in showImageModal, I expect the error to go away. However, setting the state of a another component by means of refs and globals is a bit of a React antipattern, so I would recommend to do some refactoring and use props to pass the data.

Read More

Monday, October 30, 2017

Unable to select Bootstrap dropdown in Java Selenium

Leave a Comment

I'm having a very difficult time selecting bootstrap dropdown in Selenium.

I'm new to Selenium so any suggestion and guidance would be very helpful, as what I'd love to do is just select the dropdown, type "email", and press enter during the instance.

I've gone through dozens of solutions, but none of them have worked for this specific issue.

What can I do? Please help.

Salenium

package newPackage;      import org.openqa.selenium.By;  import org.openqa.selenium.WebDriver;  import org.openqa.selenium.WebElement;  import org.openqa.selenium.chrome.ChromeDriver;  import org.openqa.selenium.interactions.Actions;      public class importLeads {    	public static void main(String args[]) throws Exception {  		  		        System.setProperty("webdriver.chrome.driver", "C:\\Users\\David\\Downloads\\Notes\\WebDriver\\chromedriver.exe");      WebDriver driver = new ChromeDriver();        //login to site      driver.get("https://demos5.softaculous.com/Mautic/s/contacts/import/new");      driver.manage().window().maximize();      driver.findElement(By.id("username")).sendKeys("admin");      driver.findElement(By.id("password")).sendKeys("password");      driver.findElement(By.className("btn")).click();      Thread.sleep(2000);        //importing Data      WebElement uploadBox = driver.findElement(By.id("lead_import_file"));      uploadBox.sendKeys("C:\\Users\\David\\Downloads\\data_file.csv");      driver.findElement(By.id("lead_import_start")).click();        //Select from dropdown      WebElement dropdownToggle = driver.findElement(By.xpath("id('lead_field_import_email_address')"));      Actions cursor = new Actions(driver);      cursor.moveToElement(dropdownToggle);      cursor.click();      cursor.perform();      Thread.sleep(1000);      WebElement weh = driver.findElement(By.id("lead_field_import_email_address_chosen"));        Actions cursor2 = new Actions(driver);      cursor2.moveToElement(weh);      cursor2.click();    	}  }


Here is the link to the data file ufile.io/vy2ws

In order for the upload of the .CSV file to work, you must be running a local version of this software. Download can be found here: https://www.mautic.org/m/asset/54:mautic-2100

Once uploaded, it should look like this where it asks to choose from the drop-down.

enter image description here

HTML

<div class="col-sm-4">     <div class="row">        <div class="form-group col-xs-12 ">           <label class="control-label" for="lead_field_import_email_address">Email address</label>                   <div class="choice-wrapper">              <select id="lead_field_import_email_address" name="lead_field_import[email_address]" class="form-control" autocomplete="false" style="display: none;">                 <option value=""></option>                 <optgroup label="Contact">                    <option value="email">Email</option>                 </optgroup>              </select>              <div class="chosen-container chosen-container-single chosen-with-drop chosen-container-active" style="width: 100%;" title="" id="lead_field_import_email_address_chosen">                 <a class="chosen-single chosen-default">                    <span>Choose one...</span>                    <div><b></b></div>                 </a>                 <div class="chosen-drop">                    <div class="chosen-search"><input type="text" autocomplete="off"></div>                    <ul class="chosen-results">                       <li class="group-result">Contact</li>                       <li class="active-result group-option" data-option-array-index="9" style="">Email</li>                    </ul>                 </div>              </div>           </div>        </div>     </div>  </div>


Replacing :

WebElement dropdownToggle = driver.findElement(By.xpath("id('lead_field_import_email_add‌​ress')"));  

to this :

WebElement dropdownToggle = driver.findElement(By.id("lead_field_import_email_address"))‌​; 

resulted in:

Starting ChromeDriver 2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f) on port 35535 Only local connections are allowed. Oct 22, 2017 1:20:49 AM org.openqa.selenium.remote.ProtocolHandshake createSession INFO: Detected dialect: OSS Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"id","selector":"lead_field_import_email_address"}   (Session info: chrome=61.0.3163.100)   (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.14393 x86_64) (WARNING: The server did not provide any stacktrace information) Command duration or timeout: 0 milliseconds For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html Build info: version: '3.6.0', revision: '6fbf3ec767', time: '2017-09-27T16:15:26.402Z' System info: host: 'DAVID-PC', ip: '192.235.0.1', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_151' Driver info: org.openqa.selenium.chrome.ChromeDriver Capabilities [{mobileEmulationEnabled=false, hasTouchScreen=false, platform=XP, acceptSslCerts=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, platformName=XP, setWindowRect=true, unexpectedAlertBehaviour=, applicationCacheEnabled=false, rotatable=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f), userDataDir=C:\Users\David\AppData\Local\Temp\scoped_dir4068_28713}, takesHeapSnapshot=true, pageLoadStrategy=normal, unhandledPromptBehavior=, databaseEnabled=false, handlesAlerts=true, version=61.0.3163.100, browserConnectionEnabled=false, nativeEvents=true, locationContextEnabled=true, cssSelectorsEnabled=true}] Session ID: ee90469095e7b1121dc2e387d8e485e6 *** Element info: {Using=id, value=lead_field_import_email_address}     at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)     at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)     at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)     at java.lang.reflect.Constructor.newInstance(Unknown Source)     at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:214)     at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:166)     at org.openqa.selenium.remote.http.JsonHttpResponseCodec.reconstructValue(JsonHttpResponseCodec.java:40)     at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:82)     at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:45)     at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:164)     at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)     at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:586)     at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:356)     at org.openqa.selenium.remote.RemoteWebDriver.findElementById(RemoteWebDriver.java:402)     at org.openqa.selenium.By$ById.findElement(By.java:218)     at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:348)     at newPackage.importLeads.main(importLeads.java:31) 

Replacing

WebElement dropdownToggle = driver.findElement(By.xpath("id('lead_field_import_email_address')"));     Actions cursor = new Actions(driver); 

with

WebElement element =  driver.findElement(By.id("lead_field_import_email_address"));     Select select = new Select(element); 

resulted in:

Starting ChromeDriver 2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f) on port 32443 Only local connections are allowed. Oct 23, 2017 1:36:09 PM org.openqa.selenium.remote.ProtocolHandshake createSession INFO: Detected dialect: OSS Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"id","selector":"lead_field_import_email_address"}   (Session info: chrome=61.0.3163.100)   (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.15063 x86_64) (WARNING: The server did not provide any stacktrace information) Command duration or timeout: 0 milliseconds For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html Build info: version: '3.6.0', revision: '6fbf3ec767', time: '2017-09-27T16:15:26.402Z' System info: host: 'HOME-PC', ip: '192.235.0.1', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_151' Driver info: org.openqa.selenium.chrome.ChromeDriver Capabilities [{mobileEmulationEnabled=false, hasTouchScreen=false, platform=XP, acceptSslCerts=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, platformName=XP, setWindowRect=true, unexpectedAlertBehaviour=, applicationCacheEnabled=false, rotatable=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f), userDataDir=C:\Users\David\AppData\Local\Temp\1\scoped_dir5416_25737}, takesHeapSnapshot=true, pageLoadStrategy=normal, unhandledPromptBehavior=, databaseEnabled=false, handlesAlerts=true, version=61.0.3163.100, browserConnectionEnabled=false, nativeEvents=true, locationContextEnabled=true, cssSelectorsEnabled=true}] Session ID: 40cde314a5a76400aceff8b625b38e3c *** Element info: {Using=id, value=lead_field_import_email_address}     at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)     at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)     at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)     at java.lang.reflect.Constructor.newInstance(Unknown Source)     at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:214)     at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:166)     at org.openqa.selenium.remote.http.JsonHttpResponseCodec.reconstructValue(JsonHttpResponseCodec.java:40)     at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:82)     at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:45)     at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:164)     at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)     at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:586)     at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:356)     at org.openqa.selenium.remote.RemoteWebDriver.findElementById(RemoteWebDriver.java:402)     at org.openqa.selenium.By$ById.findElement(By.java:218)     at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:348)     at newAutomation.importLeads.main(importLeads.java:33) 

2 Answers

Answers 1

I tried to replicate manually the steps of your code but when I load the data_file.csv and I click the Upload button:

enter image description here

nothing happens.

And, in the html, there isn't the element that you try to find:

WebElement dropdownToggle = driver.findElement(By.xpath("id('lead_field_import_email_address')")); 

That's why I wrote this comment.

I can imagine that should open something. From the informations:

  • Limit
  • Delimiter
  • Enclosure
  • Escape

I can suppose that you have to upload a file with a particular format.

EDIT

Trying locally it works. I don't understand well this part of your code:

        //Select from dropdown         WebElement dropdownToggle = driver.findElement(By.xpath("id('lead_field_import_email_address')"));         Actions cursor = new Actions(driver);         cursor.moveToElement(dropdownToggle);         cursor.click();         cursor.perform();         Thread.sleep(1000);         WebElement weh = driver.findElement(By.id("lead_field_import_email_address_chosen"));          Actions cursor2 = new Actions(driver);         cursor2.moveToElement(weh);         cursor2.click(); 

If you want to choose from the email drop-down, you could use the xpath:

WebElement we = driver.findElement(By.xpath("//div[@class='choice-wrapper']//div[@id='lead_field_import_email_address_chosen']")); 

or simply the id:

WebElement we= driver.findElement(By.id("lead_field_import_email_address_chosen")); 

and execute the interested operation.

So, for example:

    WebElement we= driver.findElement(By.id("lead_field_import_email_address_chosen"));     we.click();     we.sendKeys("email");     we.sendKeys(Keys.ENTER); 

EDIT 2

Your problem is that you use Thread.sleep(XXXX); in order to wait the elements. This is not deterministic. You must use an explicit wait.

From Explicit Waits:

An explicit wait is a code you define to wait for a certain condition to occur before proceeding further in the code. The extreme case of this is time.sleep(), which sets the condition to an exact time period to wait. There are some convenience methods provided that help you write code that will wait only as long as required. WebDriverWait in combination with ExpectedCondition is one way this can be accomplished.

So, in java you need:

WebDriverWait wait = new WebDriverWait(driver, 15); WebElement we=wait.until(ExpectedConditions.elementToBeClickable(By.id("lead_field_import_email_address_chosen"))); 

Always from the previous link:

This waits up to 15 seconds before throwing a TimeoutException unless it finds the element to return within 15 seconds. WebDriverWait by default calls the ExpectedCondition every 500 milliseconds until it returns successfully. A successful return is for ExpectedCondition type is Boolean return true or not null return value for all other ExpectedCondition types.

Finally, the entire code:

        String geckoDriver = System.getProperty("pathTo/geckodriver";         System.setProperty("webdriver.gecko.driver", geckoDriver);         WebDriver driver= new FirefoxDriver();         driver.get("http://localhost:8888/2.10.0/s/contacts/import/new");         driver.findElement(By.id("username")).sendKeys("admin");         driver.findElement(By.id("password")).sendKeys("password");         driver.findElement(By.className("btn")).click();          WebDriverWait wait = new WebDriverWait(driver, 15);          WebElement uploadBox=wait.until(ExpectedConditions.elementToBeClickable(By.id("lead_import_file")));         uploadBox.sendKeys("/pathTo/data_file.csv");         driver.findElement(By.id("lead_import_start")).click();          //Select from dropdown         WebElement we=wait.until(ExpectedConditions.elementToBeClickable(By.id("lead_field_import_email_address_chosen")));         we.click();         we.sendKeys("email");         we.sendKeys(Keys.ENTER); 

EDIT 3

With Firefox, the above code (in my tests) is ok. I noticed that you use Chrome. With Chrome, I have this problem. The solution works for me:

        //Select from dropdown         WebElement we=wait.until(ExpectedConditions.elementToBeClickable(By.id("lead_field_import_email_address_chosen")));         /*we.click();         we.sendKeys("email");*/          Actions actions = new Actions(driver);         actions.moveToElement(we);         actions.click();         actions.sendKeys("email");         actions.sendKeys(Keys.ENTER);         actions.build().perform(); 

Answers 2

Looking at the HTML you have provided, the WebElement with id="lead_field_import_email_address" is with in a Select tag. So instead of using Actions Class in this case we should try to use the Select Class instead as follows:

WebElement element =  driver.findElement(By.id("lead_field_import_email_address")); Select select = new Select(element); 

Next, we can select any of the options by invoking either selectByIndex(n), selectByValue("value") or selectByVisibleText("visible_text") method.

Read More